Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect Command-Shift-Click for OS X in javascript?

Normally, this combination opens a link as a new tab in Chrome, Firefox, and Safari for Macs. Is there any way to detect this? I know of jquery's event.which, but it gives a value of 1, which is indistinguishable from a simple left click.

The use case is with Backbone HTML5 pushstate, where I want to attach a 'click' event handler that does not trigger a page load for normal navigation, yet still allow users to open a link in a new tab with a ⌘-⇧-click.

like image 785
sye Avatar asked Mar 10 '26 01:03

sye


1 Answers

You can use the event's metaKey and shiftKey properties:

$(window).click(function(e) {
  if(e.metaKey && e.shiftKey) {
    console.log("Command+Shift+Click");
  } else {
    console.log("Other click");
  }
});

so if, for instance, you are doing #! routing instead of actually following urls, and want command or command+shift to do normal behavior (open up in a new tab), you would have something like

function followLink(e) {
  if(!e.metaKey) e.preventDefault();
  yourApp.navigate('/link');
}
like image 148
Alex Churchill Avatar answered Mar 12 '26 16:03

Alex Churchill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!