6

I need to generate keyup events in IE 8 using native DOM functions (no jQuery). The following code generates, fires, and receives the event, but the keyCode is always 0. How do I properly pass the keyCode?

<form><input id="me" type="submit" /></form>

<script type="text/javascript">
var me = document.getElementById("me");
me.attachEvent("onkeyup", function(e) {
  alert(e.keyCode); // => 0
});

document.getElementById("me").fireEvent('onkeyup', 13);
</script>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
ktusznio
  • 3,585
  • 3
  • 22
  • 21

2 Answers2

11

Figured it out. The solution is to create an event object, assign the keycode, and fire it from the node.

var e = document.createEventObject("KeyboardEvent");
e.keyCode = keyCode;

node.fireEvent("onkeyup", e);
ktusznio
  • 3,585
  • 3
  • 22
  • 21
  • 6
    Awesome, thanks for sharing your sol'n. For reference, in jQuery it would amount to: `e = jQuery.Event("keyup"); e.keyCode = 13; $(node).trigger(e);` – ampersand Sep 23 '11 at 16:10
  • From IE9 forward and for all other browsers you use createEvent() and dispatchEvent() rather than createEventObject and fireEvent(). The leading 'on' in the event name is also dropped. See http://stackoverflow.com/a/2490876/921640 – ClearCrescendo May 14 '15 at 10:26
  • It is not clear how do you define the element to trigger the event. Could you please explain it or extend the answer. Thank you. – Yevgeniy Afanasyev Jun 26 '15 at 00:43
  • 1
    @YevgeniyAfanasyev it can be any element gotten via `document.getElementById` or similar methods. – ktusznio Jul 30 '15 at 18:43
0
e = e || window.event;
keycode = e.keyCode || e.which;

That will make events work in all browsers. Also, I prefer to use me.onkeyup = function(e) { ... }, but that' just personal preference (I know the drawbacks of this method, but I have clever ways to work around them)

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • Both `e` and `e.keyCode` are defined so that code doesn't change `e` in any way. Unfortunately, `e.keyCode` comes in set to `0`. Am I passing the `13` properly? – ktusznio Sep 22 '11 at 17:14
  • I'm not familiar with `fireEvent()`, but I don't think so. It seems more like you're passing an extra argument to the function. – Niet the Dark Absol Sep 22 '11 at 17:17