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

JqueryEventsKeyboardClick

Jquery Problem Overview


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?

Jquery Solutions


Solution 1 - Jquery

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.

Solution 2 - Jquery

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
  }
});

Solution 3 - Jquery

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');
            }
     }

Solution 4 - Jquery

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>

Solution 5 - Jquery

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>

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
Questiondaniel smithView Question on Stackoverflow
Solution 1 - JquerykkyyView Answer on Stackoverflow
Solution 2 - JquerycletusView Answer on Stackoverflow
Solution 3 - JqueryArun Prasad E SView Answer on Stackoverflow
Solution 4 - Jqueryvr_driverView Answer on Stackoverflow
Solution 5 - Jqueryhp-01View Answer on Stackoverflow