Most modern browsers support the commands ctrl+click
or command+click
or similar to open links in a new tab or a new window.
In an application, I want the link to get disabled on clicking. But only, if the target is the same window (if it, for instance, opens in a new tab, I don't want the link to become disabled since it is reasonable to click it again).
I did some tries and debugged the event object that gets created on click - but I cannot find any information about whether the target is a new tab or a new window.
Known workaround: Certainly it is possible to check whether a certain key had been pressed while clicking a specific link, an easy thing - but since these commands vary from browser to browser and from OS to OS, one would have to define a complicated mapping and who nows exactly what the user has configured and so on.
Is there any reliable way of determining, whether the location should be opened in a new tab or window?
Here you have a working example: http://jsfiddle.net/pioul/eCuNU/4/
This script will allow the click on the link only if the link is going to open in a new tab/window, based on the target="_blank"
attribute.
HTML:
<a href="http://google.fr" target="_blank">new window</a>
<a href="http://google.fr" target="_self">same window 1</a>
<a href="http://google.fr" target="">same window 2</a>
jQuery:
$("a").bind("click", function(e){
if($(this).attr("target") != "_blank"){
e.preventDefault();
}
});
EDIT:
You can take into account ctrl+clicks like this:
$("a").bind("click", function(e){
if($(this).attr("target") != "_blank"){
if(!e.ctrlKey){
e.preventDefault();
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With