Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript - detect ctrl key pressed or up, keypress event doesn't trigger

I see some similar questions here (like JavaScript: Check if CTRL button was pressed) but my problem is actually the event triggering. My js code:

    // Listen to keyboard. 
    window.onkeypress = listenToTheKey;
    window.onkeyup = listenToKeyUp;

    /*
        Gets the key pressed and send a request to the associated function
        @input key
    */
    function listenToTheKey(e)
    {
        if (editFlag == 0)
        {
            // If delete key is pressed calls delete
            if (e.keyCode == 46)
                deleteNode();

            // If insert key is pressed calls add blank
            if (e.keyCode == 45)
                createBlank();

            if (e.keyCode == 17)
                ctrlFlag = 1;
        }
    }

The event triggers for any other keys except the ctrl.
I need to also trigger it for ctrl.
I can't use jQuery/prototype/whatever so those solutions are not acceptable.

So... how can I detect the ctrl?

like image 675
zozo Avatar asked Feb 21 '12 09:02

zozo


People also ask

How do you detect if a key has been pressed in JavaScript?

Using JavaScript In plain JavaScript, you can use the EventTarget. addEventListener() method to listen for keyup event. When it occurs, check the keyCode 's value to see if an Enter key is pressed.

How do you check if Enter is pressed?

To check if an “enter” key is pressed inside a textbox, just bind the keypress() to the textbox. $('#textbox'). keypress(function(event){ var keycode = (event.

Which event captures a keypress in JavaScript?

The onkeypress event occurs when the user presses a key (on the keyboard).


3 Answers

Try using if (e.ctrlKey).

MDN: event.ctrlKey

like image 51
Ash Clarke Avatar answered Oct 20 '22 10:10

Ash Clarke


Using onkeydown rather than onkeypress may help.

From http://www.w3schools.com/jsref/event_onkeypress.asp

Note: The onkeypress event is not fired for all keys (e.g. ALT, CTRL, SHIFT, ESC) in all browsers. To detect only whether the user has pressed a key, use the onkeydown event instead, because it works for all keys.

like image 33
Danielle Cerisier Avatar answered Oct 20 '22 12:10

Danielle Cerisier


Your event has a property named ctrlKey. You can check this to look if the key was pressed or not. See snippet below for more control like keys.

function detectspecialkeys(e){
    var evtobj=window.event? event : e
    if (evtobj.altKey || evtobj.ctrlKey || evtobj.shiftKey)
        alert("you pressed one of the 'Alt', 'Ctrl', or 'Shift' keys")
}
document.onkeypress=detectspecialkeys
like image 42
Rick Hoving Avatar answered Oct 20 '22 10:10

Rick Hoving