JavaScript: Check if CTRL button was pressed

Javascript

Javascript Problem Overview


I need to check if the CTRL button was pressed while I am clicking on a control on my html page using JavaScript.

How can I do this?

Javascript Solutions


Solution 1 - Javascript

Try looking in the event object.

e.g.

document.body.onclick = function (e) {
   if (e.ctrlKey) {
      alert("ctr key was pressed during the click");
   }
}

<p>Click me, and sometimes hold CTRL down!</p>

Solution 2 - Javascript

I did it using cntrlIsPressed global flag; also takes care of select all option using Control + A

// Check whether control button is pressed
$(document).keydown(function(event) {
    if (event.which == "17")
        cntrlIsPressed = true;
    else if (event.which == 65 && cntrlIsPressed) {
        // Cntrl+  A
        selectAllRows();
    }
});

$(document).keyup(function() {
    cntrlIsPressed = false;
});

var cntrlIsPressed = false;

Solution 3 - Javascript

I use this and works fine

<a  href="" onclick="return Details(event)" ></a>

function Details(event) {
            if (event.ctrlKey) {
                alert('Ctrl down');
            }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser324589457View Question on Stackoverflow
Solution 1 - JavascriptCharles MaView Answer on Stackoverflow
Solution 2 - JavascriptSacky SanView Answer on Stackoverflow
Solution 3 - JavascriptArun Prasad E SView Answer on Stackoverflow