Determine if users want to open the link in a new window or tab (Mac and Windows)

I have a link that, in order to optimize the page response / traffic, I process the event clickusing a javascript handler click. On clickI load only part of the page. But the link url is correct and opening it on a separate tab will open the page correctly.

But when the user clicks the CMD-Click link (to open the link in a new tab), the handler runs click, and the page is NOT open in a new tab. Basically, I disabled CMD-Click functionality (open in a new tab). How can I detect this in code to make CMD-Click work as expected. (On 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
})

Should I write OS / browser code for the solution TODOabove? (I am using jQuery)

+4
source share
1 answer

Check the properties event ctrlKey, shiftKeyand metaKey. This tells you that the user held control, shift or command, respectively. Also check what is whichnot 2, which means that the user clicked the link on 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
});
+8
source

Source: https://habr.com/ru/post/1548194/


All Articles