Lets say I want to intercept certain anchor element links and track them. I have the following which works.
HTML
<a href="/foo" data-mytracking="fooclicked">go to foo</a>
JS
$('a[data-mytracking]').click((event) => {
event.preventDefault();
// Do some synchronous code to log tracking
console.log(event.target.getAttribute('data-mytracking'), event.target.href);
window.location = event.target.href;
});
Is there a way to have this click code still intercept middle clicks or right click "open in a new tab"? I know I can do this if I make the href="javascript:void(0)". But then people lose the ability to open in a new tab.
Some browsers have auxclick event. You also can track event.which to track middle button.
$("a[data-mytracking]").on('click', function(ev) {
if( ev.which== 2 ) {
e.preventDefault();
// do smth else
}
});
Opening through a contextmenu is possibly not trackable, but you can have oncontextmenu event.
P.S. at least Chrome doesn't trigger click on opening a new tab with a middle button. But it does trigger mouseup.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With