3

I have problem with focus event handling 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 output is:

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

it seems that IE8 queues all focus requests and executes event handlers after current function ends.

Is there any workaround to force IE8 to behave nicely 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>

2 Answers 2

4

IE delays the actual focus until after the function test() is completed, so I am afraid you have to use a construction 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 will have time to set the focus on txt1 before the second part is executed.

By the way, you should omit the prefix javascript: in the onclick and onfocus attributes. The javascript: prefix should only be used in a href attribute.

1
  • +1 for the javascript: prefix used in href. Spent 2 days because of that, had href = "" instead of href="javascript:". Jun 12, 2020 at 13:29
0

I've seen this issue with older versions of IE. Some people have come up with very creative answers for this, sometimes with a lot of code, such as using a timer, etc. The solution is really a one liner. I've confirmed this works in older versions of IE as well as modern browsers like Chrome.

What I've done to make this work in jQuery is this, if you know the index of the field you want to table to:

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

Or in plain ole' JavaScript.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.