I'm trying to simualte keyboard events in webpage through javascript since Actions is not supported in safari browser.
To Start with I created a simple form (given below) and trying to tab through the text boxes but it didn't work.
Java script used: (ubuntu and chrome browser). I fired the script in the chrome browser console.
var pressTabKey = document.createEvent("KeyboardEvent");
pressTabKey.initKeyboardEvent("keypress", true, true, null, false, false, false, false, 9, 0);
document.getElementById('1234').focus();
document.getElementById('1234').dispatchEvent(pressTabKey);
HTML Form:
<html>
<head>
</head>
<body>
<p>Test Page </p>
<form>
<input id="1234" type="text" value="Enter Here">
<br>
<br>
<input id="1235" type="text" value="Enter Here">
</form>
</body>
</html>
Hope this helps:
https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events
Example: I create an event and use dispatchEvent() to trigger it:
var pressTabKey = new Event('keydown');
document.getElementById('1234').addEventListener('keydown', function() { alert("hi!"); });
document.getElementById('1234').dispatchEvent(pressTabKey);
The function createEvent() is deprecated: https://developer.mozilla.org/en-US/docs/Web/API/Document/createEvent
EDIT:
You could simply read the key code from a keydown or keypress event, like so:
http://jsfiddle.net/adrielD/me9q1qu6/
HTML
<p>Test Page </p>
<form>
<input id="1234" type="text" value="Enter Here"><br>
<input id="1235" type="text" value="Enter Here">
</form>
JS:
var tab1 = document.getElementById("1234");
var tab2 = document.getElementById("1235");
tab1.addEventListener("keydown", function(event) {
if(event.keyCode == 9) {
event.preventDefault();
tab2.focus();
}
});
tab2.addEventListener("keydown", function(event) {
if(event.keyCode == 9) {
event.preventDefault();
tab1.focus();
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With