Zoltan
Zoltan

Reputation: 163

jQuery to add _blank to external link

I'm making a script which, automatically ads target="_blank" to all external links. The problem is that, the script also makes the internal absolute links open in a new tab. You can check the problem on this test link: http://www.fairfood.org/testtest/

$("a").filter(function () {
    return this.hostname && this.hostname !== location.hostname;
}).each(function () {
    $(this).attr({
        target: "_blank",
        title: "Visit " + this.href + " (click to open in a new window)"
    });
});

Does anybody know how to fix this?

Any help is much appreciated.

Upvotes: 2

Views: 1628

Answers (4)

pixelbobby
pixelbobby

Reputation: 4440

You can use a single jQuery selector to do this:

$('a').not('a[href*="fairfood.org/"]').each(function(){
    $(this).attr({target: "_blank", title: "Visit " + 
            $(this).href + " (click to open in a new window)"});
});

Upvotes: 1

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385174

www.yourhost.com is not the same as yourhost.com, so when your links don't match, this isn't working.

You can just take out the www. if you know that this will always lead to a valid URI.

(Also, your use of .each is almost redundant, as jQuery is already knowledgeable about element sets; however, you need it for this.href. Just something to be aware of.)

$("a").filter(function() {
    return this.hostname &&
           this.hostname.replace(/^www\./, '') !==
              location.hostname.replace(/^www\./, '');
}).each(function() {
   $(this).attr({
       target: "_blank",
       title: "Visit " + this.href + " (click to open in a new window)"
    });
});

Live example.

Upvotes: 10

jensgram
jensgram

Reputation: 31508

As commented above, www.fairfood.org is not the same host as fairfood.org. Don't treat a WWW and a non-WWW host as one. Instead, choose whether to use www or not; and then stick with it throughout the site.

(This has the added benefit of avoiding potential duplicate content penalties.)

Upvotes: 0

two7s_clash
two7s_clash

Reputation: 5827

fairfood.org and www.fairfood.org are technically different hostnames. Get rid of www before you test if you want both to work in your script.

Upvotes: 0

Related Questions