6

I'm trying to trigger a keydown of the tab key in JavaScript.

Scenario: 2 HTML input elements. Initially focus is on the 1st input, then wait 3 seconds, then simulate pressing of the tab key, which should set focus to the 2nd input.

Issue: Dispatching a tab keydown event does nothing.

Fiddles:

I am after a JavaScript solution. No jQuery thanks.

Fiddle example using simulant.js below:

HTML:

<input id="first">
<input id="second">
<p>Dispatching Tab keydown event in 3 seconds... <span id="done" style="color:red"></span></p>

JavaScript:

//simulates keydown of the tab key
function simulateTab() {
    var TAB_KEY = 9;    
    simulant.fire(document, 'keydown', { keyCode: TAB_KEY });
}

//focus 'first' input
document.getElementById('first').focus();

//focus 'second' input after 3 seconds
setTimeout(function(){
    simulateTab();
    document.getElementById('done').innerHTML = 'Done!';
}, 3000);
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Andrew
  • 5,525
  • 5
  • 36
  • 40
  • 1
    possible duplicate of [Simulate keypress without jquery](http://stackoverflow.com/questions/17323279/simulate-keypress-without-jquery) – Kevin L Jul 30 '14 at 14:04
  • The apparent 'duplicate' solution did not work. – Andrew Jul 30 '14 at 14:17
  • 4
    I have looked through all answers with both duplicate questions, none of them work. No wonder none of the answers have been marked as accepted! – Andrew Jul 30 '14 at 14:25

0 Answers0