How can I check if a key is pressed during the click event with jQuery?
Asked Answered
C

5

118

I would like to catch a click event with jQuery and be able to tell if a key was pressed at the same time so I can fork within the callback function based on the keypress event.

For example:

$("button").click(function() {
    if([KEYPRESSED WHILE CLICKED]) {
        // Do something...
    } else {
        // Do something different...
    }
});

Is this possible at all or how can it be done if it is possible?

Chagres answered 15/3, 2010 at 7:25 Comment(0)
D
195

You can easily detect the shift, alt and control keys from the event properties;

$("button").click(function(evt) {
  if (evt.ctrlKey)
    alert('Ctrl down');
  if (evt.altKey)
    alert('Alt down');
  // ...
});

See quirksmode for more properties. If you want to detect other keys, see cletus's answer.

Doggish answered 15/3, 2010 at 7:33 Comment(4)
I don't see that property on the jQuery Event object: api.jquery.com/category/events/event-objectJealousy
Well, as the page says, "Most properties from the original event are copied over and normalized to the new event object." ctrlKey, altKey etc. are part of the ecmascript standard (see the first link on the aforementioned jquery api page), so (at least in decent browsers) the event object usually has also those properties set.Doggish
Quirks mode only says these are defined in a key event .. no mention about a mouse event.Ingar
You can even detect Mac OS X's command key using if (e.metaKey) alert('Command down'). Here's a nice article about key events in JS unixpapa.com/js/key.htmlHonan
J
52

You need to separately track the key status using keydown() and keyup():

var ctrlPressed = false;
$(window).keydown(function(evt) {
  if (evt.which == 17) { // ctrl
    ctrlPressed = true;
  }
}).keyup(function(evt) {
  if (evt.which == 17) { // ctrl
    ctrlPressed = false;
  }
});

See the list of key codes. Now you can check that:

$("button").click(function() {
  if (ctrlPressed) {
    // do something
  } else {
    // do something else
  }
});
Jealousy answered 15/3, 2010 at 7:32 Comment(3)
One down side of this method (not that I know a better way) is if you are detecting the ALT key, and the user ALT-Tabs to another window, then the keyup event is not detected by the browser because it occurred on another application. From that point, jquery thinks the key is down, until they keyup within your jquery app. This only matters with the ALT key, as far as I can imagine.Vasya
For Mac OS X that would be Cmd-Tab, but I think the principal still holdsQuincyquindecagon
Or Ctrl+Tab for changing browser's tabUnwell
V
9

I was able to use it with JavaScript alone

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

  function Show(event) {
            if (event.ctrlKey) { 
                 alert('Ctrl down');
            }
     }
Valene answered 16/7, 2016 at 7:11 Comment(1)
Further to that, I made a small adjustment and a pen: codepen.io/vr_driver/pen/YRoRYOSavagism
S
5

Without stealing @Arun Prasad's thunder, here is a pure JS snippet I rehashed to stop the default action, which would otherwise open a new window if CTL+click is pressed.

function Show(event) 
{
  if (event.ctrlKey) 
  {
    alert('Ctrl held down which clicked');
  } 
  else 
  {
    alert('Ctrl NOT pressed');
  }
  return false
}
<p>Hold down CTL on the link to get a different message</p>

<a href="" onclick="return Show(event)">click me</a>
Savagism answered 7/12, 2018 at 3:39 Comment(0)
R
0

let isCtrlClicked = false;
let selectedContainer = [];
document.addEventListener("keydown", function(e) {
  if (e.key === "Control") {
    isCtrlClicked = true;
  }
});

document.addEventListener("keyup", function(e) {
  if (e.key === "Control") {
    isCtrlClicked = false;
    selectedContainer.forEach(item => {
      item.elem.style.backgroundColor = "";
      item.elem.dataset.isAlreaySelected = "0";
      delete item.elem.dataset.position;
    });
    selectedContainer = selectedContainer.filter(item => item.active);
    console.log(selectedContainer);
    selectedContainer = [];
  }
});

const main = document.getElementById("main");
for (let i = 0; i < main.childElementCount; i++) {
  main.children[i].dataset.isAlreaySelected = "0";
  main.children[i].addEventListener("click", function(e) {
    const isAlreaySelected = e.currentTarget.dataset.isAlreaySelected;
    const position = parseInt(e.currentTarget.dataset.position);
    if (isCtrlClicked && isAlreaySelected == "0") {
      e.currentTarget.style.backgroundColor = "rgba(0,0,200,0.2)";
      selectedContainer.push({
        elem: e.currentTarget,
        active: true
      });
      e.currentTarget.dataset.position = selectedContainer.length - 1;
      e.currentTarget.dataset.isAlreaySelected = "1";
    } else {
      e.currentTarget.style.backgroundColor = "";
      if (position > -1) {
        e.currentTarget.dataset.isAlreaySelected = "0";
        delete e.currentTarget.dataset.position;
        selectedContainer[position].active = false;
      }
    }
  });
}
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

#main {
  display: flex;
}

#main>div {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: auto;
  text-align: center;
  border: 1px solid grey;
  width: 100px;
  height: 100px;
  margin: 1rem;
}
<div id="main">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
  <div>6</div>
</div>
Rosemarie answered 3/2, 2022 at 12:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.