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

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

<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> 
+6
source share
2 answers

Figured it out. The solution is to create an event object, assign a key code, and start it from node.

 var e = document.createEventObject("KeyboardEvent"); e.keyCode = keyCode; node.fireEvent("onkeyup", e); 
+11
source
 e = e || window.event; keycode = e.keyCode || e.which; 

This will make events work in all browsers. Also, I prefer to use me.onkeyup = function(e) { ... } , but it's "just a personal preference (I know the flaws of this method, but I have smart ways to get around them)

0
source

Source: https://habr.com/ru/post/897847/


All Articles