Skip to content

Instantly share code, notes, and snippets.

@sukima
Created March 28, 2014 01:12
Show Gist options
  • Save sukima/9822950 to your computer and use it in GitHub Desktop.
Save sukima/9822950 to your computer and use it in GitHub Desktop.
This is how I managed to facilitate keyboard events in multiple browsers
// <input id="my-input-element" type="text" value="foo"/>
var evt, node = document.getElementById('my-input-element');
// Have to use dispatchEvent/fireEvent because jQuery.trigger will not
// fire an event attached via addEventListener. Each environment has an
// unusual way to trigger a keyup event.
if (node.dispatchEvent) {
// Sane browsers
try {
// Chrome, Safari, Firefox
evt = new KeyboardEvent('keyup');
} catch (e) {
// PhantomJS (wat!)
evt = document.createEvent('KeyboardEvent');
evt.initEvent('keyup', true, false);
}
evt.keyCode = 32;
node.dispatchEvent(evt);
} else {
// IE 8
evt = document.createEventObject('KeyboardEvent');
evt.keyCode = 32;
node.fireEvent('onkeyup', evt);
}
@bhawin-boom
Copy link

Isn't keyCode as read only property

@richardlopes-daitangroup

https://stackoverflow.com/a/26979893. This works for me.

var keyPressed = null;

function keyPress(key) {
  var event = document.createEvent('Event');
  event.keyCode = key; // Deprecated, prefer .key instead.
  event.key = key;
  event.initEvent('keydown');
  document.dispatchEvent(event);
}

document.addEventListener('keydown', function(e){
   keyPressed = e.key;
});

keyPress(37)
alert(keyPressed);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment