45

I need some help to create jquery script :)
I have some of link like this on my HTML.

<a href="http://google.com">Google</a>
<a href="/">Home</a>
<a href="http://www.gusdecool.com/">Home</a>
<a href="contactus.html">Contact Us</a>

And now i want jQuery to check all of the link on my page. if that link is outside of my server (my server is gusdecool.com). Then add target="_blank". and the result will be like this

<a href="http://google.com" target="_blank">Google</a>
<a href="/">Home</a>
<a href="http://www.gusdecool.com/">Home</a>
<a href="contactus.html">Contact Us</a>
GusDeCooL
  • 5,639
  • 17
  • 68
  • 102
  • Possible duplicate of [How do I add target="\_blank" to a link within a specified div?](http://stackoverflow.com/questions/804256/how-do-i-add-target-blank-to-a-link-within-a-specified-div) – chimos May 12 '16 at 13:27

15 Answers15

70

assuming that all external links will start with http:// you could do this:

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

Moin Zaman
  • 25,281
  • 6
  • 70
  • 74
  • nope, please see my comment for Joakim for the explanation :) – GusDeCooL Oct 26 '11 at 11:03
  • 1
    an external site could still start only with *www* and any other link that contains the `gusdecool` keyword (ex : a subdomain such as `http://sub.gusdecool.com`) is still considered external to the current webpage. – gion_13 Oct 26 '11 at 11:13
  • 12
    I came across this thread after searching for a quick solution for external links and I think the selector should be `$('a[href^="http://"], a[href^="https://"]').` to match https links as well. – Jörn Jul 26 '13 at 11:09
  • 1
    This will not include https sites, you should probably just use `$('a[href^="http"]').not('a[href*=gusdecool]').attr('target','_blank');` – redanimalwar May 06 '17 at 14:02
  • I needed to set "gusdecool" into single or double quotes to make the code work. – johnnydoe82 Sep 02 '20 at 15:42
19
$('a').each(function() {
   var a = new RegExp('/' + window.location.host + '/');
   if (!a.test(this.href)) {
      $(this).attr("target","_blank");
   }
});

This was from css-tricks.com, seems to work pretty well.

Ryan Doom
  • 2,407
  • 1
  • 16
  • 13
  • 3
    I have two questions: 1) does this work with relative links like `Home`? 2) why don't you put `var a = new RegExp('/' + window.location.host + '/');` befor the loop? – Falk Jan 22 '15 at 09:06
14
$('a[href^=http]:not([href^=http://www.gusdecool.com/])').attr('target','_blank');

Of course, this works only if all the external links start with the http protocol. You should adapt this code to suite your needs (suchs as links without protocols, or with different protocols).

UPDATE :

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

It selects all the a elements that have their href attribute starting with a web page address (with or without protocol) and do not point to your site's address and changes their target attribute to _blank.

gion_13
  • 41,171
  • 10
  • 96
  • 108
13

This function seems to be easier if you have a subdomain:

$('a').attr('target', function() {
  if(this.host == location.host) return '_self'
  else return '_blank'
});
Andy Hoffman
  • 18,436
  • 4
  • 42
  • 61
Guyom
  • 131
  • 1
  • 5
  • This is the best answer to me, since totally agnostic (i.e. not hard-written stuffs) and fully explicit. +1 – keepAlive Jun 01 '20 at 13:16
3
jQuery(document).ready(function(){
    target_luar();
});    
function target_luar(){
    try{
        if(top.location != location) {
            jQuery("a[href^='http']")
              .not("[href*='"+location.host+"']")
              .attr('target','_blank');
        }
    } catch(err) { }
}

Demo : Demo jQuery External Link

Pavel Strakhov
  • 39,123
  • 5
  • 88
  • 127
Hendriono
  • 39
  • 3
3

Global function to open external links in a new window:

$(function(){ // document ready

    $("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)"
        });
    });

});
Pedro Dias
  • 41
  • 4
  • A word of caution (applies to many solutions on this page): if you have a **mailto** link, it will also receive a **target** attribute, which could lead to undesirable behavior (in Chrome, it works but also opens an extra blank tab). – Jonathan Lidbeck Feb 12 '16 at 03:35
3

Putting it all together we get the following.. Wait for it all to load, select only links starting with http or https, check if the link point to the same domain (internal) or another domain (external), add appropriate target if match found..

$(window).load(function() {
    $('a[href^="http"]').attr('target', function() {
      if(this.host == location.host) return '_self'
      else return '_blank'
    });
});
boateng
  • 910
  • 11
  • 21
1

This is such a brilliant site I learned so much from it :

If you do it this way you do not need to worry about http or https (handy while developing)

$('a[href^="http"]')
        .not('a[href*='+ location.hostname +']')
        .attr('target','_blank');

Kaya M
  • 11
  • 1
1

You can see all external link whith http and https


jQuery('a[href^="https://"],a[href^="http://"]').not("a[href*='"+ window.location.host +"']").each(function() {
  
    console.log(jQuery(this).attr('href'))
});

And you can add _blank like this

jQuery('a[href^="https://"],a[href^="http://"]').not("a[href*='"+ window.location.host +"']").attr('_target','blank');
Mahdi Bashirpour
  • 17,147
  • 12
  • 117
  • 144
1

Check each linkobject $(link).attr("href"), if that starts with http:// then its an outgoing link (?). Then assign the .attr("target", "_blank").

$(a).function(){
    if($(this).attr("href").substring(0,3) == "http" && <!-- CHECK ITS NOT YOUR SITE URL -->){
       $(this).attr("target", "_blank"); 
    }
};

Hope this helps.

Joakim Serholt
  • 403
  • 5
  • 17
  • well kind of it is.. you will end up at the site, but it is still an outgoing link? – Joakim Serholt Oct 26 '11 at 11:03
  • my purpose create this plugin is to make sure my visitor didn't leave my website if click a link except if that link target is inside of my website. That why i need to make special rule for outgoing link. – GusDeCooL Oct 26 '11 at 11:08
  • @GusDeCooL I don't think its a very good idea to stop people leaving your site to go to external sites if they wish to. They will find other ways and get frustrated if you try and stop them. Or am I misunderstanding you? – Moin Zaman Oct 26 '11 at 13:26
  • 2
    He doesn't want to stop people from leaving his site. He just want external links to be _blank to make it easy for them to find their way back to his site once they are done with the external link's site. Using _blank for that purpose would be one way to do it. – Joakim Serholt Oct 26 '11 at 15:20
  • @JoakimBörjesson Thank you for explain it to Moin :) – GusDeCooL Oct 26 '11 at 15:35
1

You could use jQuery's $.each function to iterate over all Anchor tags, perform the needed check and set the "target" attribute using $(this).attr("target","_blank");

Example (Not tested but should work):

$('a').each(function(index) {
    var link = $(this).attr("href");
    if(link.substring(0,7) == "http://")
        $(this).attr("target", "_blank");
});

Shai.

Shai Mishali
  • 9,224
  • 4
  • 56
  • 83
1

Here's a fiddle demonstrating an answer using raw JS (not jQuery): http://jsfiddle.net/Xwqmm/

And here's the code:

var as = document.getElementsByTagName('a');
var re = /^https?:\/\/([^\/]*)\//;
for (var i = 0, l = as.length; i < l; i++) {
    var href = as[i].href;
    var matches = href.match(re);
    if (matches[1] && matches[1] != "gusdecool.com") {
        as[i].setAttribute("target","_blank");
    }
}
Benjie
  • 7,701
  • 5
  • 29
  • 44
0

Try:

$('a[href^="http://"]')
        .not('a[href*='+ location.hostname +']')
        .attr('target','_blank');
0
<div id="myLinks"><a href="http://google.com">Google</a><a href="/">Home</a><a href="http://www.gusdecool.com/">Home</a>
<a href="contactus.html">Contact Us</a></div>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('#myLinks a').attr('target', '_blank');
});
</script>
0

You could use filter -

$("a").filter(function () {
    return this.indexOf('http://') > -1 && this.indexOf('gusdecool') == -1 
}).attr("target","_blank");  
ipr101
  • 24,096
  • 8
  • 59
  • 61