KeyboardEvent in Chrome, keyCode is 0

Andrija picture Andrija · Jan 20, 2012 · Viewed 36.6k times · Source

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>

Answer

Philip Nuzhnyy picture Philip Nuzhnyy · Sep 21, 2012

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