Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KeyboardEvent in Chrome, keyCode is 0

I am trying to set keyCode on dispatched event object .

On button click, event is raised on textbox control to simulating keydown event. Event is raised successfully, but keyCode is 0. I need to send event object with correct keyCode to textbox. I've been using code from here.

How to set keyCode value in dispatched event?

<html>     <head>           </head>     <body>         <input type="button" id="btn" value="Click"></input>         <input type="text" id="txt"></input>         <script>             document.getElementById('btn').addEventListener("click", btnClick);             document.getElementById('txt').addEventListener("keydown", txtKeydown);                       function btnClick(e) {                 var txt = document.getElementById('txt');                                 var dispatchKeyboardEvent = function(target, initKeyboradEvent_args) {                     var e = document.createEvent("KeyboardEvents");                     e.initKeyboardEvent.apply(e, Array.prototype.slice.call(arguments, 1));                     e.keyCode = 83;                     e.charCode = 0;                     target.dispatchEvent(e);                 };                  var canceled = !dispatchKeyboardEvent(txt,                 'keydown', true, true,  // type, bubbles, cancelable                 window,  // window                 's',  // key                 0, // location: 0=standard, 1=left, 2=right, 3=numpad, 4=mobile, 5=joystick                 false, false, false);  // Ctr, Alt, Shift             }              function txtKeydown(e) {                 console.dir(e);                 console.log(e.keyCode);             }          </script>     </body> </html> 
like image 969
Andrija Avatar asked Jan 20 '12 14:01

Andrija


People also ask

What is e keyCode === 13?

key 13 keycode is for ENTER key.

What is the keyCode for Enter key?

Tests of onkeydown reveal that when the "normal" enter key is pressed, keyCode=13 and location=0; when the numpad enter is pressed, keyCode=13 and location=3. So the following code can be used to set key==13 if the enter, key==176 if numpad enter: window. onkeydown=function(ev) { var e= ev || window.


1 Answers

I am amazed that this bug has been sitting there for ages. There seems to be a workaround using generic events. Here's a demo: http://jsbin.com/awenaq/3

like image 177
Philip Nuzhnyy Avatar answered Sep 22 '22 20:09

Philip Nuzhnyy