24

I tried many variations to put target="_blank" in links with jQuery, but I can't get it to work.

Here's my code:

var thumbfile = "<?php echo $smit_iturl_v; ?>"; jQuery(document).ready(function () { var actualHost = jQuery.trim(jQuery.url.attr("host")); jQuery("a img").each(function (i) { if (jQuery.trim(jQuery.url.setUrl(jQuery(this).attr("src")).attr("host")) == actualHost && (jQuery.url.setUrl(jQuery(this).attr("src")).attr("path")).indexOf("wp-content") != -1 && isImage(jQuery.url.setUrl(jQuery(this).attr("src")).attr("file"))) { var parentTag = jQuery(this).parent().get(0).tagName; parentTag = parentTag.toLowerCase(); if (parentTag == "a" && jQuery.url.setUrl(jQuery(this).parent().attr("href")).attr("host") == actualHost && jQuery.url.setUrl(jQuery(this).parent().attr("href")).attr("path").indexOf("wp-content") != -1 && isImage(jQuery(this).parent().attr("href"))) { var description = (jQuery(this).attr("alt") == "") ? jQuery(this).attr("title") : jQuery(this).attr("alt"); jQuery(this).parent().attr("href", thumbfile + "?title=" + jQuery(this).attr("title") + "&description=" + description + "&url=" + stripDomain(jQuery(this).parent().attr("href")) ); } } }); 

How can I do it?

4 Answers 4

84

Too much information! This should work fine:

$("a").attr("target","_blank"); 

See the example here http://jsbin.com/evexi/edit. It works perfectly.

Sign up to request clarification or add additional context in comments.

2 Comments

If you only want to open external links in a new window then this regex might be helpful. $("a[href^='http']").attr('target','_blank');
I wrote this a while back, but just used it yet again myself for a new site I'm working on: dpatrickcaldwell.blogspot.com/2010/03/…
16

Since you are iterating over the image elements that are childs of an anchor, at the beginning of the loop you can set it:

//... jQuery("a img").each(function (i) { // 'this' is the img element, you should get the parent anchor jQuery(this).parent().attr('target', '_blank'); //... }); 

Comments

11

To add to the awesome simplicity of this answer, which was super helpful by the way, you can target multiple types of links for example:

$("#whatever_id a, #another_id, #yet_another, #etc").attr("target","_blank"); 

Just keep the different id's separated by commas.

Comments

10

You could give all the links you want to open in a new window a class, eg 'target-blank';

<a href='#' class='any existing classes target-blank'>Opens in a new window</a> 

then add a drop of jQuery

$("a.target-blank").attr('target','_blank'); 

valid xhtml and a DOM that understands target='_blank'!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.