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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Rajesh
  • 24,354
  • 5
  • 48
  • 79
  • 1
    Its not available now https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/initKeyboardEvent – Anand Singh Nov 26 '15 at 14:27
  • You can use this https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/KeyboardEvent – Anand Singh Nov 26 '15 at 14:30
  • @AnandSingh [MDN](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent). Both `KeyboardEvent.initKeyEvent` and `KeyboardEvent.initKeyboardEvent` have been marked as deprecated. – Rajesh Nov 26 '15 at 14:38

1 Answers1

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.

Community
  • 1
  • 1
Ramanlfc
  • 8,283
  • 1
  • 18
  • 24
  • I have updated my [Fiddle](http://jsfiddle.net/RajeshDixit/e7p69mhq/2/). Now error is now thrown but `Tab` is not getting fired. I suppose there is some silly mistake. Can you please help? – Rajesh Nov 26 '15 at 14:34
  • Also I was a bit confused with `keyCode`, `charCode` and `code`. – Rajesh Nov 26 '15 at 14:40