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>
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>
Share
Improve this question
edited Nov 14, 2019 at 12:27
Brian Tompsett - 汤莱恩
5,89372 gold badges61 silver badges133 bronze badges
asked Sep 11, 2012 at 8:05
Jacek FrancuzJacek Francuz
2,4988 gold badges45 silver badges62 bronze badges
1
- 1 Use onmousedown or add oncontextmenu - for inspiration, see stackoverflow.com/questions/8893269/… ("How to capture links" - stackoverflow.com/questions/8927208/…) – Rob W Commented Sep 11, 2012 at 8:07
2 Answers
Reset to default 13Try 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>
Nowadays we can use pointerdown
. It works for both mouse and finger touch.
From Pointer events docs:
Pointer events are DOM events that are fired for a pointing device. They are designed to create a single DOM event model to handle pointing input devices such as a mouse, pen/stylus or touch (such as one or more fingers).