Search code examples
javascripteventssequencekeypressexplorer

Keypress event sequence on IE


I just noticed that the sequence of the keypress event is not executed the same way on Firefox and IE: on Firefox, if you keypress on a focused input, the character is written in the box, then the function attached to the event is fired. On IE it is the opposite.

So here's my problem, i have two input text next to each other, when i write a single character in the first one i want the second one to get the focus just after. This is working perfectly on Firefox, but not on IE because it switches to the second input before the character is even written in the first one ...

Here is a simplification of the code i'm using (both elements are text input):

        var one = document.getElementById('one');
        var two = document.getElementById('two');

        one.addEventListener('keypress', function(e) {
            e.target.nextElementSibling.focus();
        });

How should i fix that? How do i indicate to switch the focus AFTER the key pressed is appeared on the screen?


Solution

  • I guess you can use setTimeout like this:

    var one = document.getElementById('one');
    var two = document.getElementById('two');
    
    one.addEventListener('keypress', function(e) {
        setTimeout((function(elem){
            return function(){
                elem.focus();
            };
        })(e.target.nextElementSibling),0);
    });
    <input id="one" type="text"/><input id="two" type="text"/>

    The setTimeout will fire the function on the next stack of execution, so after the element is filled.