79

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?

Martin Thoma
  • 124,992
  • 159
  • 614
  • 958
user324589457
  • 845
  • 1
  • 7
  • 6

3 Answers3

151

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>
Mikael Dúi Bolinder
  • 2,080
  • 2
  • 19
  • 44
Charles Ma
  • 47,141
  • 22
  • 87
  • 101
  • 3
    FYI when you use this on a mac with "ctrl-click = right click" you still get the behavior of browser menu opening. – Andrew K Nov 07 '14 at 19:00
  • 6
    If you need to detect the Mac OS X's command key check the ```metaKey``` property of the event object ```e.metaKey``` – romek Apr 15 '17 at 17:46
  • How can you get the state of the Ctrl key being pressed or not, outside an event? The use case is setting a property of a control on asynchronous initialization depending on the state of a modifier key. – Dan Dascalescu Oct 09 '19 at 03:55
  • In javascript's event model you ask to check if CTRL button was down. The keypressed event is returned when a key is released again; not all browsers appear to generate such keypressed events for modifier keys like CTRL, SHIFT and others. – db-inf Nov 06 '22 at 07:49
7

I use this and works fine

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

function Details(event) {
            if (event.ctrlKey) {
                alert('Ctrl down');
            }
}
Arun Prasad E S
  • 9,489
  • 8
  • 74
  • 87
  • 1
    What does this add to the accepted answer? How is this answer any better, or even meaningfully different? – Dan Dascalescu Oct 09 '19 at 03:41
  • Different requirements like what? When this page shows up in Google searches, so do *all* answers in it, not just this one. So my question still stands. – Dan Dascalescu Oct 10 '19 at 00:06
  • 2
    This is a helpful addition to the accepted answer because it is adding the event handler from html, not from within the javascript. – cmyr Dec 26 '20 at 16:36
  • 1
    @cmyr I'd argue otherwise, setting event handlers from HTML is a security risk and should be forbidden using [CSP policies](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP). – Ruan Mendes Feb 27 '23 at 13:06
6

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;
Sacky San
  • 1,535
  • 21
  • 26