Javascript Event for "Open in new Tab"
Asked Answered
H

2

12

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>
Hebner answered 11/9, 2012 at 8:5 Comment(1)
Use onmousedown or add oncontextmenu - for inspiration, see #8893769 ("How to capture links" - #8927708)Josselyn
S
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>
Stoneblind answered 11/9, 2012 at 8:9 Comment(2)
@FlexJack Did you actually get the "open link in new tab" option to open the some_other_url ?Phago
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.Numbat
N
0

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).

Numbat answered 16/7 at 9:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.