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:
- Using KeyboardEvent & dispatchEvent - http://jsfiddle.net/dH9ZE/
- Using simulant.js - http://jsfiddle.net/3E5dB/
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);