JSFiddle - React, Tailwind, and code Playground

by ThiefMaster

HTML

<a class="track" href="http://www.example.com" target="_blank">new tab</a><br>
<a class="track" href="http://www.example.com">same tab</a><br>

JavaScript

var middleClickTarget = null;

// We track the element where the middle mouse was pressed and released. This avoids cases where the
// mousedown event happens on a link but the mouseup somewhere else and vice versa. We could move the
// mousedown event into the onclick event for links but this way it's more organized.
$(document).on('mousedown', function(e) {
    if(e.button === 1) {
        middleClickTarget = e.target;
    }
}).on('mouseup', function(e) {
    if(e.button === 1) {
        middleClickTarget = null;
    }    
});

// When there's a middle button mouseup event on a link AND it's the element that initially received the
// mousedown event we have a middle click that is actually going to open a new tab. So let's track the click.
$('a.track').on('mouseup', function(e) {
    if(e.button !== 1 || this !== middleClickTarget) {
        return;
    }
    
    console.log('middle click on link: ' + this.href);
});

$('a.track[target!="_blank"]').on('click', function(e) {
    var href = $(this).attr('href');
    if(e.shiftKey) {
        // that means the user wants a new window! don't intercept and just log.
        console.log('shift+left click on link (new tab/window): ' + this.href);
    }
    else {
        console.log('left click on link (same tab, delay): ' + this.href);
        // usually this would be an AJAX request and hopefull MUCH faster than 500s ;)
        setTimeout(function() {
            location.href = href;
        }, 500);
        e.preventDefault();
    }
});

$('a.track[target="_blank"]').on('click', function(e) {
    console.log('left click on link (new tab): ' + this.href);
});