Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS onClick not executing when we opening right click->open in new tab

Tags:

javascript

I have some onClick events in elements, so they get called when a user clicks on a link. This works well, and looks like this:

foo

Unfortunately, if a user opens the link in a new tab (e.g right click->open in new tab), my onLinkClick function does NOT get called. This happens with Firefox (various versions, including the latest one - 1.5.0.1).

Does anyone know if there is a way to work around that and catch even the "open in new tab" clicks/events?

Thanks!

like image 577
Ashish Arora Avatar asked Jun 18 '13 11:06

Ashish Arora


1 Answers

You need to use the preventDefault method for right click.

In jQuery you can do this as:

$(document).on("mousedown", "a", function(e) {
   if( e.which === 3 ) {
      e.preventDefault();
      //do something now
   }
});

Use 1 for left click, 2 for middle click and 3 for right click.

In JavaScript:

<a href="#" onmousedown="mouseDown(event);">aaa</a>​​​​​​​​​​​​​​​​​​​​​​​​​​​

function mouseDown(e) {
  e = e || window.event;
  switch (e.which) {
    case 1: alert('left'); break;
    case 2: alert('middle'); break;
    case 3: alert('right'); break; 
  }
}​

Demo

like image 171
Chankey Pathak Avatar answered Oct 31 '22 11:10

Chankey Pathak