JavaScript or jQuery event handlers for "Ctrl"/"Shift" + mouse left button click

JavascriptJqueryEvents

Javascript Problem Overview


Is it possible to handle such events as:

  • Ctrl + mouse left button click;
  • Shift + mouse left button click;
  • Alt + mouse left button click by using JavaScript, jQuery or other framework.

If it is possible, please give a code example for it.

Javascript Solutions


Solution 1 - Javascript

You can do something like this (jQuery for the click handler, but any framework works on the part that matters):

$(selector).click(function(e) {
  if(e.shiftKey) {
    //Shift-Click
  }
  if(e.ctrlKey) {
    //Ctrl+Click
  }
  if(e.altKey) {
    //Alt+Click
  }
});

Just handle whichever you want inside an if inside the click handler like I have above.

Solution 2 - Javascript

If you use JQuery plugin called hotkeys you can handle the special keys below.

$(document).bind('keydown', 'Ctrl+c', fn);

Solution 3 - Javascript

More recently I encountered a problem with using e.ctrlKey in that, it does not work on MACs. In a Macintosh, the same effect is achieved using Command+Click.

Since most of the answers above are already assuming usage of jQuery, you can simply use the e.metaKey property which is made available by jQuery.

e.g.

$(selector).click(function(e) {
  if(e.shiftKey) {
    //Shift-Click
  }
  if(e.metaKey) {
    //Ctrl+Click on Windows & Command+Click on Mac.
  }
  if(e.altKey) {
    //Alt+Click
  }
});

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
QuestionAntonView Question on Stackoverflow
Solution 1 - JavascriptNick CraverView Answer on Stackoverflow
Solution 2 - JavascriptDhavalView Answer on Stackoverflow
Solution 3 - JavascriptSunny R GuptaView Answer on Stackoverflow