11

I have the following problem: I use Javascript onclick event to change href of a link. It works like a charm but only if user just clicks a link. If "Open in new tab" feature is used for the link - onclick event will not fire and href will never change. Is there any way to handle such an event? Perhaps with jQuery or some other JS Framework?

Example:

<a href="some_url" onclick="this.href = 'some_other_url'">Link</a>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Jacek Francuz
  • 2,420
  • 8
  • 45
  • 61
  • 1
    Use onmousedown or add oncontextmenu - for inspiration, see http://stackoverflow.com/questions/8893269/what-is-the-most-reliable-way-to-hide-spoof-the-referrer-in-javascript ("How to capture links" - http://stackoverflow.com/questions/8927208/catching-event-when-following-a-link) – Rob W Sep 11 '12 at 08:07

1 Answers1

13

Try to change

<a href="some_url" onclick="this.href = 'some_other_url'">Link</a>

to

<a href="some_url" onmousedown="this.href = 'some_other_url'">Link</a>
ianarko
  • 402
  • 3
  • 12
Mateusz Rogulski
  • 7,357
  • 7
  • 44
  • 62
  • @FlexJack Did you actually get the "open link in new tab" option to open the `some_other_url` ? – Magne Apr 16 '14 at 20:28
  • It's worth noting that `onmmousedown` doesn't fire **on mobile devices** when the user tap-hold the link (to open in new tab). **But it still fires** when the user taps the link. – M Imam Pratama Jul 14 '23 at 14:10