0

I want to fire Tab key's keypress event on a specific condition, but I'm getting error.

Error: Uncaught TypeError: event.initKeyEvent is not a function

Code

function simulateKeyPress(element) {
  console.log("Simulate")
  var event = document.createEvent('KeyboardEvent'); // create a key event

  // define the event
  event.initKeyEvent("keypress", // typeArg,
    true, // canBubbleArg,
    true, // cancelableArg,           
    null, // viewArg,  Specifies UIEvent.view. This value may be null.
    false, // ctrlKeyArg,
    false, // altKeyArg,
    false, // shiftKeyArg,
    false, // metaKeyArg,
    9, // keyCodeArg,
    9); // charCodeArg);
  element.dispatchEvent(event);
}

function keyPress(event) {
  simulateKeyPress(this);
}

(function() {
  var inputs = document.getElementsByTagName("input");
  for (var i = 0; i < inputs.length; i++) {
    inputs[i].addEventListener("keypress", keyPress);
  }
})()
<input type="text">
<input type="text">

I have been taking following links for reference but still unable to get it working.

Following is the link of Fiddle

Edit

Updated Fiddle that uses KeyboardEvent, but still unable to fire Tab keypress event.

Also, I'm not looking for jQuery.

3

1 Answer 1

1
 console.log(typeof (event.initKeyEvent)); // returns undefined 

and MDN docs say :

This feature has been removed from the Web standards. Though some browsers may still support it, it is in the process of being dropped. Do not use it in old or new projects. Pages or Web apps using it may break at any time.

Do not use this method any more, use the KeyboardEvent() constructor instead.

Sign up to request clarification or add additional context in comments.

2 Comments

I have updated my Fiddle. Now error is now thrown but Tab is not getting fired. I suppose there is some silly mistake. Can you please help?
Also I was a bit confused with keyCode, charCode and code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.