JS onClick fails when we open the right click-> open in a new tab

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

Foo

Unfortunately, if a user opens a link in a new tab (for example, right-click-> open in a new tab), my onLinkClick function is NOT called. This happens with Firefox (various versions, including the most recent - 1.5.0.1).

Does anyone know if there is a way around this and even catch β€œopen in a new tab” clicks / events?

Thanks!

+4
source share
1 answer

For a right click you need to use the preventDefault method.

In jQuery you can do it like:

 $(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

+1
source

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


All Articles