6

I have a link that, in order to optimize the page response/traffic, I handle its click event with a javascript click handler. On click, I only load some part of the page. But the link's URL is correct and opening it in a standalone tab would open the page correctly.

But when the user presses CMD-Click on the link (to open the link in new tab), the click handler runs and the page is NOT opened in new tab. Basically I disabled the CMD-Click (open in new tab) functionality. How can I detect this in code in order to make CMD-Click work as expected. (In Windows CMD is replaced by Ctrl.)?

$(".link").on("click", function(event) {

    if (/* TODO: how to detect if the user CMD/Ctrl-clicked the link? */) {
        return true;
    }

    // ... load only necessary things for normal clicks
})

Do I have to write OS/browser specific code to solve the TODO above? (I use jQuery)

Gabriel Petrovay
  • 20,476
  • 22
  • 97
  • 168
  • 1
    What would you do to Right mouse button/open in new tab? Mouse scroll click? Shift + click? – Yury Tarabanko Jul 12 '14 at 17:53
  • 2
    @YuryTarabanko: `event.which` can handle the middle-click. Right-clicking and selecting open in new tab won't fire the event handler in the first place. – josh3736 Jul 12 '14 at 17:56
  • @josh3736 I believe there is a better way to tell if you need to load the entire page. Maybe `X-Requested-With` header will do the trick – Yury Tarabanko Jul 12 '14 at 17:59
  • 1
    may this help you: http://stackoverflow.com/questions/10660360/command-click-doesnt-open-a-new-tab-but-middle-click-does – Black Sheep Jul 12 '14 at 18:00
  • There are many keys that change the default behavior, not just `ctrl`. You're better off using something like [`filter-altered-clicks`](https://github.com/bfred-it/filter-altered-clicks) to handle it for you. – fregante Oct 10 '16 at 17:02

1 Answers1

11

Check the event's ctrlKey, shiftKey, and metaKey properties. These tell you if the user was holding control, shift, or command respectively. Also check that which is not 2, which means the user middle-clicked the link.

$(".link").on("click", function(event) {

    if (event.ctrlKey || event.shiftKey || event.metaKey || event.which == 2) {
        return true;
    }

    // ... load only necessary things for normal clicks
});
josh3736
  • 139,160
  • 33
  • 216
  • 263