Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add target="_blank" to all links BUT internal site links

I have the following code that will add target="_blank" to all links:

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

How would I re-write the above code to target all links except links that are internal.

IE:

http://www.my-site.com/ = internal link

http://www.other-site.com/ = external link

Also how would I target any links that do not begin with http:// but are not internal?

I am looking for a jQuery solution.

like image 692
L84 Avatar asked Dec 27 '22 02:12

L84


2 Answers

Just chain your selectors:

$("a[href^='http']:not([href^='http://www.mysite.com'])").attr("target","_blank");

This will select all links starting with http (so not relative internals) but not starting with http://www.mysite.com (so not the absolute internals either).

like image 123
Niels Keurentjes Avatar answered Jan 10 '23 06:01

Niels Keurentjes


I use the following bit of JavaScript when using jQuery. It also adds a class to external links and includes tracking of outgoing links in Google Analytics. Just remove it if you don't use Google Analytics.

You can use a more specific selector if you don't want this to hit all links on a page, for example $("#main a[href^=http]").

$("a[href^=http]")
  .each(function(){
    // this part checks if the link is external
    if (this.href.indexOf(location.hostname) == -1){
      // add a class for external links
      $(this).addClass("ext")
        // make the link open in a new tab/window
        .attr({ "target":"_blank", "rel":"external" })
        // track clicks of external links if you use Google Analytics
        .click(function(){
          _gaq.push(["_trackEvent", "Outgoing link", "click", $(this).attr("href")]);
        });
    }
  });
like image 22
Marcel Avatar answered Jan 10 '23 06:01

Marcel