Gabriel Petrovay Gabriel Petrovay - 1 month ago 6
jQuery Question

Detect if the user wanted to open link in new window or tab (Mac and Windows)

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)

Answer

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