Skip to content

Instantly share code, notes, and snippets.

@callumlocke
Last active August 29, 2015 14:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save callumlocke/9a27325f1fb786d71630 to your computer and use it in GitHub Desktop.
Save callumlocke/9a27325f1fb786d71630 to your computer and use it in GitHub Desktop.
Find out whether a click is really a click.
"use strict";
module.exports = function isSimpleClick(event) {
var isLeft = true;
var which = event.which;
if (!which && event.button != null) {
which = event.button & 1 ? 1 : event.button & 2 ? 3 : event.button & 4 ? 2 : 0;
}
if (which) {
if (which === 3) isLeft = false; // right
if (which === 2) isLeft = false; // middle
}
return !(
!isLeft || // not a left click
event.metaKey || // "open link in new tab" (mac)
event.ctrlKey || // "open link in new tab" (windows/linux)
event.shiftKey || // "open link in new window" (all)
event.altKey // "save link as" (all)
);
};

isSimpleClick(event)

Function that takes a mouse event and tells you whether it's a simple left-click.

  • Works around browser inconsistencies in event.which (using jQuery's technique).
  • Checks that no modifier keys are pressed.
element.addEventListener('click', function (event) {
  if (!isSimpleClick(event)) return;
  
  // ok, do something...
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment