I have a scenario where I have to prepare a JS method where Tab key should fire . i.e. When the Function is executed Tab button click should fire. preferably using Key code.
Asked
Active
Viewed 349 times
0
-
Possible duplicate of [Firing a Keyboard Event in JavaScript](http://stackoverflow.com/questions/961532/firing-a-keyboard-event-in-javascript) – JYoThI May 22 '17 at 09:37
-
"Tab button click" makes no sense. Do you mean clicking a button should dispatch a [*keyboard event*](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/KeyboardEvent) which uses the same *key* value as the Tab key? For *key* use "Tab", for *which* use `9`. – RobG May 22 '17 at 09:51
-
yes exactly, function should execute or dispatch what ever keycode supplied – lokanath das May 22 '17 at 09:56
1 Answers
0
You can dispatch keyboard events, but the results might be less than overwhelming.
As shown below, you can dispatch an event with appropriate properties, but in some browsers the values are empty and the browser virtually ignores it. You can tab to the button and press "Enter" to click it. It dispatches a tab, but focus doesn't move and the associated event doesn't report the values set in the constructor.
Typing into the input shows the type of result you should get. Try it in lots of browsers.
function showEventProperties(evt) {
document.getElementById('details').innerHTML = ['type','key','code','keyIdentifier','charCode','which','keyCode'].map(function(key) {
return key + ': ' + evt[key];
}).join('<br>');
}
function sendTab(node) {
var evt = new KeyboardEvent('keypress', {
'view': window,
'bubbles': true,
'key': 'Tab',
'charCode': 9,
'keyCode': 9,
'which': 9
});
node.dispatchEvent(evt);
}
window.onload = function() {
document.addEventListener('keypress', showEventProperties, false);
}
<input onkeypress="showEventProperties(event)">
<br>
<button onclick="sendTab(this)">Do tab</button><button>Next button</button>
<p id="details"></p>
You can also try the older initKeyEvent.

RobG
- 142,382
- 31
- 172
- 209
-
Thanks a lot, but its not working in IE :( . Actually I am struggling with this, because my real problem is different. this one I am using as a work around. Please find the link for it, if better solution you can suggest. [link] (https://stackoverflow.com/questions/44062232/how-to-validate-shifttab-button-click-in-js) – lokanath das May 22 '17 at 12:00