IE Focus Event Handler Delay

I have a problem handling focus events in the code below in IE8. I get the following output:

LOG: set focus txt1
LOG: set focus txt2
LOG: txt1 focus
LOG: txt2 focus

but in all other browsers the conclusion is:

LOG: set focus txt1
LOG: txt1 focus
LOG: set focus txt2
LOG: txt2 focus

IE8 seems to queue all focus requests and execute event handlers after the current function completes.

Is there a workaround to make IE8 behave like other browsers?

<html>
<head>
</head>
<body>
<script>
        function test(){
            console.log('set focus txt1');
            document.getElementById('txt1').focus();
            console.log('set focus txt2');
            document.getElementById('txt2').focus();
        }
    </script>
<input id="txt1" type="text" onfocus="javascript:console.log('txt1 focus')" style="width:100px" />
<input id="txt2" type="text" onfocus="javascript:console.log('txt2 focus')" style="width:100px" />
<button value="Click" onclick="javascript:test()"></button>
</body>
</html>
+3
source share
2 answers

IE delays the actual focus until the function test()is completed, so I'm afraid you need to use a construct like:

function test(){
    console.log('set focus txt1');
    document.getElementById('txt1').focus();

    window.setTimeout(function() {
        console.log('set focus txt2');
        document.getElementById('txt2').focus();
    }, 1);
}

Here I postpone the second part of the function so that IE has time to set focus on txt1before the second part is executed.

, javascript: onclick onfocus. javascript: href.

+3

IE. , , , .. . , IE, , Chrome.

, jQuery, , , :

 $('input:text')[5].focus();

ole 'JavaScript.

document.getElementsByName("elementname")[0].focus();
0

All Articles