How to detect if user it trying to open a link in a new tab?
You can examine the ctrlKey
, shiftKey
, and metaKey
properties of the event object. If either is true, the key control, shift, or meta (Apple's command) key is being held and you should allow the default link action to proceed. Otherwise, you use preventDefault
to stop the link action and handle it with javascript instead.
Add target="_blank"
to your anchor markup, so the default link behavior is opening a new tab. Otherwise it will open on top of the current page (that may be desired).
Here's the javascript, either way:
document.getElementById("mylink").onclick = function(evnt) {
if (
evnt.ctrlKey ||
evnt.shiftKey ||
evnt.metaKey || // apple
(evnt.button && evnt.button == 1) // middle click, >IE9 + everyone else
){
return;
}
evnt.preventDefault();
alert("clicked");
return false;
}
Fiddle: http://jsfiddle.net/6byrt0wu/
Documentation
- MDN Events - https://developer.mozilla.org/en-US/docs/Web/API/Event
Event.ctrlKey
- https://developer.mozilla.org/en-US/docs/Web/API/event.ctrlKeyEvent.shiftKey
- https://developer.mozilla.org/en-US/docs/Web/API/event.shiftKeyEvent.metaKey
- https://developer.mozilla.org/en-US/docs/Web/API/event.metaKeya
tag - https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a