Mr.
Mr.

Reputation: 10102

HTML\Javascript - get ATL\CTRL\SHIFT key press

Is there the ability to capture any key press? i.e. Ctrl + Shift + Alt key press (with no other key press).

In the snippet below (checked under Chrome), I am able to capture the shift only when other "regular" key was pressed.

UPDATE:

<html>
<head>
    <script>
        function onKeyPressed(event) {
            event = event || window.event;
            var code = event.keyCode;
            var key = String.fromCharCode(event.keyCode);
            var shift = event.shiftKey;
            var alt = event.altKey;
            var ctrl = event.ctrlKey;
            var which = event.which;
            var str = "code = " + code + "\n" +
                      "key = " + key + "\n" +
                      "shift = " + shift + "\n" +
                      "alt = " + alt + "\n" +
                      "ctrl = " + ctrl + "\n" +
                      "which = " + which;
            alert(str);
        };

        function onClick(event) {
            event = event || window.event;
            var x = event.clientX;
            var y = event.clientY;
            var str = "x = " + x + "\n" +
                      "y = " + y;
            alert(str);
        };

        function onKeyUp(event) {
            alert("onKeyUp");
        };

        function onKeyDown(event) {
            alert("onKeyDown");
        }
    </script>
</head>
<body onmousedown="onClick(event)" onkeypress="onKeyPressed(event)" onkeyup="onKeyUp(event)" onkeydown="onKeyDown(event)"></body>
</html>

How can those keys be captured?

Upvotes: 3

Views: 5662

Answers (3)

Spudley
Spudley

Reputation: 168695

There's a very nice new JS library that does a great job of tracking keyboard events in the browser.

It's called Mousetrap. Here's the link: http://craig.is/killing/mice

Hope that helps.

Upvotes: 4

IanStallings
IanStallings

Reputation: 816

AFAIK You have to use the keyup or keydown event to capture the shift, keyPress does not capture it. Check out this list of keys captured by each event if you need more details. Since shift is a modifier key it's not captured. Why this is the case I cannot explain.

Upvotes: 2

Renato Gama
Renato Gama

Reputation: 16519

Is jQuery allowed? If so take a look at this:

http://www.stepanreznikov.com/js-shortcuts/

otherwise you may give @Max Gherkins suggestion a chance

Upvotes: 2

Related Questions