jQuery: go to URL with target="_blank"
Solution 1
You need to open a new window:
window.open(url);
https://developer.mozilla.org/en-US/docs/DOM/window.open
Solution 2
Use,
var url = $(this).attr('href');
window.open(url, '_blank');
Update:the href
is better off being retrieved with prop since it will return the full url and it's slightly faster.
var url = $(this).prop('href');
Solution 3
Question: How can I open the href in the new window or tab with jQuery?
var url = $(this).attr('href').attr('target','_blank');
Solution 4
The .ready
function is used to insert the attribute once the page has finished loading.
$(document).ready(function() {
$("class name or id a.your class name").attr({"target" : "_blank"})
})
Solution 5
Detect if a target attribute was used and contains "_blank". For mobile devices that don't like "_blank", this is a reliable alternative.
$('.someSelector').bind('touchend click', function() {
var url = $('a', this).prop('href');
var target = $('a', this).prop('target');
if(url) {
// # open in new window if "_blank" used
if(target == '_blank') {
window.open(url, target);
} else {
window.location = url;
}
}
});
Dimitri Vorontzov
Updated on July 05, 2022Comments
-
Dimitri Vorontzov almost 2 years
I am using this bit of jQuery code to get href of the link:
var url = $(this).attr('href');
-- and this bit of code to go to that href:
window.location = url;
Everything is just the way I want it, except the new page opens in the same window as the previous one, and I want it to open in a new window or tab (something that in plain html would have been achieved by using target="_blank" formula).
Question: How can I open the href in the new window or tab with jQuery?
Thank you for your help!
-
Dimitri Vorontzov almost 13 yearsThank you. That's just what I needed. Another quick question: is there a way to tell the browser to open a new tab rather than a new window?
-
Dimitri Vorontzov almost 13 yearsThank you. No, not a pop-up. Just a normal window. Normally I would just let html do the job, but a prior bit of code I use in the same menu disables the default behavior for all the links.
-
Christopher Armstrong almost 13 yearsI believe it depends upon how the browser is configured (i.e. a setting to open pop-ups in tabs or windows).
-
Nathan Wailes about 6 yearsJust a heads-up for future readers: I was using
jQuery("a").prop("target", "_blank");
without enclosing it in$document.ready
and it wasn't working in Chrome, but once I enclosed it in the$document.ready()
call, it started working.