Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulating keyboard event through javascript

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>
like image 840
user1925406 Avatar asked Sep 13 '15 08:09

user1925406


1 Answers

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();
    }
});
like image 92
adrield Avatar answered Sep 22 '22 04:09

adrield