Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I generate a keyup event with a specific keycode in IE8?

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>
like image 427
ktusznio Avatar asked Sep 22 '11 17:09

ktusznio


People also ask

How do you use Keyup events?

The keyup event is fired when a key is released. The keydown and keyup events provide a code indicating which key is pressed, while keypress indicates which character was entered. For example, a lowercase "a" will be reported as 65 by keydown and keyup , but as 97 by keypress .

What is Onkeyup event?

The onkeyup event occurs when the user releases a key (on the keyboard). Tip: The order of events related to the onkeyup event: onkeydown. onkeypress.

What is keycode for tab?

JavaScript tab key code is 9. Use the keydown event to get the tab key code or char code in JavaScript.


1 Answers

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);
like image 131
ktusznio Avatar answered Oct 06 '22 15:10

ktusznio