[jQuery] Open links in a new window or tab

Adding a target="_blank" attribute to your links will open them in a new window or tab. It's possible to use jQuery to open a link or links in a new window without directly editing html source codes.

You can add  target="_blank" to your link(s) using the attr method:

$(document).ready(function(){
$("a[href^='http']").attr('target','_blank');
});

Now, every link will be opened in a new window. You might also specify the relevant class:

$(document).ready(function() {
$("class name").attr({"target" : "_blank"})
})

As you know, if you add a class, it should be .class_name. And if you add an id, it should be #id_name.

It's possible to use window.open:

$(document).ready(function(){
$('.class_name').click(function(){
window.open(this.href);
return false;
});
});

If you want to limit to specific URLs:

$(document).ready(function(){
$('a[href=http://www.google.com]').click(function(){
window.open(this.href);
return false;
});
});
// Source: http://befused.com/

Then, all links with www.google.com will be opened in a new window.

If you want to open all links within comments in WordPress in a new window, you can replace the class section with #comments a.

$(window).ready(function(){
//adds target blank to all comment links in WordPress
$('#comments a').each(function(){
$(this).attr('target','_blank');
});
});
// Source: wordpress.org

Of course, you might use a WordPress hook to do this instead of jQuery (Please refer to this post.) There are also WordPress plugins which open external links in a new window, such as Open external links in a new window.


Leave a Comment