Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I intercept middle click and new tab link clicks?

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.

like image 249
Daniel Moses Avatar asked Oct 20 '25 08:10

Daniel Moses


1 Answers

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.

like image 147
shukshin.ivan Avatar answered Oct 21 '25 20:10

shukshin.ivan