28

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>
Community
  • 1
  • 1
Andrija
  • 14,037
  • 18
  • 60
  • 87
  • There is a very clever work-around for this, please see: http://stackoverflow.com/questions/10455626/keydown-simulation-in-chrome-fires-normally-but-not-the-correct-key/10520017#10520017 This will allow you to set the properties you need, and send a keyup/down event. Sample code included. – Orwellophile May 09 '12 at 16:26

6 Answers6

37

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

Philip Nuzhnyy
  • 4,630
  • 1
  • 25
  • 17
  • 10
    This bug *still* exists! – B T Apr 25 '14 at 05:57
  • @Philip could you explain the demo? It seems like you've entered the keycodes for the buttons pressed, which isn't a workaround to chrome not being able to tell which key is pressed. – ProblemsOfSumit Dec 05 '14 at 09:24
  • @Sumit: the demo shows how to use a generic event instead of the KeyboardEvent when **manually triggering** events. – Philip Nuzhnyy Dec 07 '14 at 19:52
  • 2
    The bug is in Google bug tracker for quite a long time: https://code.google.com/p/chromium/issues/detail?id=327853&q=KeyboardEvent&colspec=ID%20Pri%20M%20Stars%20ReleaseBlock%20Cr%20Status%20Owner%20Summary%20OS%20Modified – Maxim Gritsenko Aug 07 '15 at 11:16
  • This is unlikely to be fixed since [`keyCode` is deprecated](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode). `keyCode` can *only* be set when the `KeyboardEvent` is created from a `WebKeyboardEvent`, and you can't call that constructor from JS. See [here](https://cs.chromium.org/chromium/src/third_party/WebKit/Source/core/events/KeyboardEvent.cpp?l=78) and [here](https://cs.chromium.org/chromium/src/third_party/WebKit/Source/core/events/KeyboardEvent.cpp?l=129). – Jordan Milne Sep 22 '16 at 00:26
10

It looks like it's been a bit since you asked this so you may have already found the answer to your question. In case you haven't though, there is a bug in Webkit as was pointed out in this SO question that causes the keyCode to always be 0. Apparently there's not much you can do until they fix it. Sadly it doesn't look like anyone is really working on it though. It's not the answer you want to hear, but it's really the only answer anyone can give you for this right now.

Community
  • 1
  • 1
Justin Warkentin
  • 9,856
  • 4
  • 35
  • 35
0

I have faced same issue with Android devices like, Sony Xperia and HTC Devices. So i found alternate solution: please refer to my answer for this question KeyCode Returns 0 Always

Community
  • 1
  • 1
Raghu
  • 174
  • 13
0

If you have jQuery:

$.Event(event, { keyCode: 13 });

This is the intended use.
Source.

medik
  • 1,174
  • 12
  • 17
0

This happens because (as others have stated) the KeyboardEvent object (which uses charCode instead of keyCode) is being called instead of the Event object. When you are using:

function txtKeydown(e) {
    console.dir(e);
    console.log(e.keyCode);
}

if you're getting a 0 printed to the console, try using e.charCode instead of e.keyCode

refer to MDN web docs for more information regarding KeyboardEvent: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent

Mado
  • 45
  • 7
-3

It is not a bug... this feature is being weeded out, deprecated, forbidden, whateva' the name will be tomorrow... You cannot rely on this feature to work for long. ...and is a wide open security risk... find another way to do what you are trying to do. Consult the MOZILLA specs and you will see the BIG BAD RED BANNER which warns to avoid this like the plague. They will not fix it, by returning 0 they effectively stop the bleeding without changing the code except in one place where it always zaps the keyCode to 0.

fib Littul
  • 21
  • 5