Question

I want to know if ctrl,space,alt,capslock,shift like keys are pressed in my keyboard. When i do

String.fromCharCode(e.keyCode)

,it returns blank value for these keys but when I do

alert($.trim(String.fromCharCode(e.keyCode))=='')

Then it return false for all keys except space bar.So it would be great if someone may tell me to get the keydown event of these keys

Was it helpful?

Solution

Vanilla JavaScript:

For other constants, see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent

window.onkeydown = function (e) {
    switch (e.keyCode) {
        case KeyboardEvent.DOM_VK_SPACE:
            alert('space bar!');
            break;
        case KeyboardEvent.DOM_VK_CAPS_LOCK:
            alert('CAPS LOCK!');
            break;
        case KeyboardEvent.DOM_VK_CONTROL:
            alert('control!');
            break;
        case KeyboardEvent.DOM_VK_SHIFT:
            alert('shift!');
            break;
        case KeyboardEvent.DOM_VK_ALT:
            alert('alt!');
            break;
    }
};

UPDATED FOR REQUIREMENT TO AVOID CASES:

Per the following test, the only numeric values that will, after trimming (and not including numbers not corresponding to the average keyboard), be reduced to an empty string are 9,10,11,12,13,32. Looking at https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Virtual_key_codes , the only ones that correspond are tab, clear, return, and space .

// Run in Firefox where trim() is supported (without need for jQuery):
var arr = [];
for (var i=0; i < 0xFFFF; i++) {
    if (String.fromCharCode(i).trim() == '') {
        arr.push(i);
    }
}

In other words, your own test is not going to catch all cases.

So you have to use numeric comparisons based on the info at https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Virtual_key_codes and BASED ON EXACTLY WHAT CHARACTERS YOU NEED TO INCLUDE (or exclude).

For example, if you consider the cancel key, help key, back space, tab, etc. all to be of the type you mentioned, you can do:

window.onkeydown = function (e) {
    if (e.keyCode < 0x30) {
        alert('Special key pressed!');
    }
};

As you can see, this allows for us to find a whole group of characters within a short amount of code (e.g., without using case). (But if we don't know exactly which characters you want to include or exclude, we can't give you a more precise answer.)

OTHER TIPS

NOTE:

charCode is never set in the keydown and keyup events. In these cases, keyCode is set instead.

you can try

$(window).keydown(function (e){
    if (e.ctrlKey) {     there are e.altKey & e.shiftKey also.
                                  for other keys use hardcoded integer values.
    alert("control");
    }
});

I'm not sure about the support of keyIdentifier but if you are using the keyup, keydown or keypress events, but you could possibly do the following. However there are no cross-browser guarantees where charcode is not defined or is zero. Not using jquery to keep things as small as possible, and only detecting the keys that you specified. See article.

Javascript

/*jslint maxerr: 50, indent: 4, browser: true */

(function () {
    "use strict";

    function addEvent(elem, event, fn) {
        if (typeof elem === "string") {
            elem = document.getElementById(elem);
        }

        function listenHandler(e) {
            var ret = fn.apply(null, arguments);

            if (ret === false) {
                e.stopPropagation();
                e.preventDefault();
            }

            return ret;
        }

        function attachHandler() {
            window.event.target = window.event.srcElement;

            var ret = fn.call(elem, window.event);

            if (ret === false) {
                window.event.returnValue = false;
                window.event.cancelBubble = true;
            }

            return ret;
        }

        if (elem.addEventListener) {
            elem.addEventListener(event, listenHandler, false);
        } else {
            elem.attachEvent("on" + event, attachHandler);
        }
    }

    function checkKeys(e) {
        if ("Alt,Shift,Control,CapsLock,U+0020".indexOf(e.keyIdentifier) !== -1) {
            alert(e.keyIdentifier);
        }      

        console.log(e.keyIdentifier);
    }

    addEvent(window, "keydown", checkKeys);
}());

On jsfiddle

Update: reading a bit furter, keyIdentifier is not supported by all browsers and so is not fullly cross-browser friendly.

3.4. New Standard Key and Character Events

The DOM3 standard abandons all hope of creating order among event.keyCode, event.which and event.charCode, and instead defines new values for keydown and keyup events. For a while it deprecated the keypress event and replaced it with the textInput event, but that was undone. Only a few browsers implemented the first version, and, so far, no browsers have implemented the newest version. Earlier versions of the specification defined attributes named event.keyIdentifier and event.keyLocation. The keyIdentifier was a string that in most cases looked like "U+0041" where the "0041" part is the unicode value of the character sent by the key when it is typed without modifiers, in this case the letter "A". For keys that didn't send unicode characters, or where the unicode value is not standardized, it was a string like "Enter", "Shift", "Left" or "F9". The keyLocation attribute gave values to distinguish among multiple keys that had the same identifier, like the left and right shift keys, or the keypad number keys. It was 0 for standard keys, 1 or 2 for left or right versions of a keys like Shift which appear twice on the keyboard, and 3 for keys on the numeric keypad.

WebKit implemented support for keyIdentifier and got it mostly right. Older versions conformed to an older version of the standard and returned two extra zeros (eg, "U+000041") but this was corrected in version 525. Windows versions of Safari and Linux versions of Chrome return bad keyIdentifier values for all of the non-number symbol keys (WebKit Bug 19906 reported in July 2008). The keyLocation attribute is always 0 or 3, so it does not distinguish between left and right modifier keys.

Konqueror returns keyIdentifier values like "Shift" and "Enter" correctly, but instead of returning the Unicode values, it returns the typed character itself, "a" or "A" instead of "U+0041". All keyLocation values are zero, except for modifiers key, which are always one, regardless of whether the left or right one was pressed.

We cannot, however expect any more browsers to implement that standard, since it has now changed. The DOM 3 standard no longer mentions event.keyIdentifier or event.keyLocation. Instead we have event.key, event.char, event.location.. So far as I know, no browser has yet implemented this new version of the DOM 3 standard.

In this standard event.char is defined only when you type a printable character, or another character with a defined code (like tab or backspace). It's basically like event.charCode except that it is the character, not the character code and can be any unicode character not just an ASCII code. Event.key is the same as event.char for printable keys. For other keys, even ones like tab or backspace that have character encodings, it is a string like 'Tab', 'Left' or 'F9'. These values are supposed to be the same on keypress events as they are on keyup and keydown events, though keypress would not be fired for those cases where event.char is null.

Note that neither of these pretends to be a keycode identifying a particular physical key on the keyboard. If you press the /? key on a US keyboard while shift is off, but press the shift key before releasing the /? key, then then on keydown you'll get event.key=='/' and on keyup you'll get event.key=='?'. The only way your Javascript program will know that those two events go together is if it happens to know that those two characters are on the same key. There is an event.locale value that is supposed to give you some clue on what type of keyboard is being used, but figuring out what keys go with what on a particular keyboard is up to you.

Clearly this abandonment of the idea of keycodes is going to cause problems, but is still probably justified. In many (most?) operating systems, I don't think the browser can actually tell which key was pressed. In the browser source code I've seen, the keycodes are generated from the the character codes, not vice versa, by simply assuming that the character came from a US keyboard. So the keycode values never really worked for non-US keyboards.

So while the keycode concept was a handly one, it isn't really practically extensible in the real world. If you want a keycode in the DOM 3 universe, you'll have to go on using the legacy event.keyCode value, which, standards or no standards, isn't going away. The DOM 3 standard seems to recognize this, and reluctantly provides an appendix with some standards for event.keyCode and the like. It casts a rather weak vote for what I called "IE keycodes" above.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top