Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How do you check if a key is pressed in jQuery?

To check if an “enter” key is pressed inside a textbox, just bind the keypress() to the textbox. $('#textbox'). keypress(function(event){ var keycode = (event.

Which jQuery event occurs when key is pressed?

The keypress() method triggers the keypress event, or attaches a function to run when a keypress event occurs. The keypress event is similar to the keydown event. The event occurs when a button is pressed down. However, the keypress event is not fired for all keys (e.g. ALT, CTRL, SHIFT, ESC).

How do you check if keypress is enter?

In plain JavaScript, you can use the EventTarget. addEventListener() method to listen for keyup event. When it occurs, check the keyCode 's value to see if an Enter key is pressed.

How do you check if a specific key is pressed JavaScript?

addEventListener('keydown', (e) => state[e. key] = true); return (key) => state. hasOwnProperty(key) && state[key] || false; })(); You can then check if a key is pressed with is_key_down('ArrowLeft') .


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.


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

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

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>