user324589457
user324589457

Reputation: 893

Check if CTRL key is pressed when clicking an element

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?

Upvotes: 83

Views: 74951

Answers (3)

Arun Prasad E S
Arun Prasad E S

Reputation: 10135

Check if CTRL button was pressed. I use this and works fine.

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

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

Upvotes: 8

Charles Ma
Charles Ma

Reputation: 49201

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>

Upvotes: 158

Sacky San
Sacky San

Reputation: 1662

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;

Upvotes: 6

Related Questions