Skip to content
Advertisement

How to detect single control keyup event but not key combinations?

It is easy to detect control key event with

document.addEventListener('keyup', handler, false);

...

function handler(e) {
    var key = e.which || e.keyCode;

    if (key == 17) { // Control key
        ...
    }
}

The problem is that any key combinations such as controlc and controlv will also trigger the event, and it seems that the event handler cannot distinguish between a single control and the control within a controlc.

What I want is to allow only a single key press-and-release, but not a key combination, to trigger the event.

Advertisement

Answer

You can actually use e.ctrlKey and e.altKey, and the value will be true or false based on whether or not those keys are pressed.

In your event, it would be something like:

if (e.ctrlKey || e.altKey) {
    return;
}

EDIT

For reference, you can view https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/ctrlKey.

This property is actually a boolean that returns whether or not the ctrl key was pressed when the event was fired.

Then, you can see that if the user decides to press the ctrl key and no other key, this method will not return and e.ctrlKey will be false, since by the time the keyUp event was fired the user had already released the key.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement