46

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>
1

15 Answers 15

71

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

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

5
  • nope, please see my comment for Joakim for the explanation :)
    – GusDeCooL
    Oct 26, 2011 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, 2011 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, 2013 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'); May 6, 2017 at 14:02
  • I needed to set "gusdecool" into single or double quotes to make the code work. Sep 2, 2020 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.

1
  • 3
    I have two questions: 1) does this work with relative links like <a href="/">Home</a>? 2) why don't you put var a = new RegExp('/' + window.location.host + '/'); befor the loop?
    – Falk
    Jan 22, 2015 at 9: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.

3
  • Nice jQuery selector! This should get voted above the selected correct answer as it is the best/fastest solution.
    – zarazan
    Apr 12, 2013 at 15:35
  • You might want to add "s? Because I'm getting unrecognized expressions. Jun 24, 2016 at 5:02
  • Using these jQuery selectors can affect javascript performance.
    – Meki
    Aug 10, 2016 at 7:29
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'
});
1
  • This is the best answer to me, since totally agnostic (i.e. not hard-written stuffs) and fully explicit. +1
    – keepAlive
    Jun 1, 2020 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

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

});
1
  • 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). Feb 12, 2016 at 3: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'
    });
});
1
  • 1
    It would be great if you could provide a short explanation of your code!
    – jonny
    Oct 2, 2018 at 18:51
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.

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.

5
  • well kind of it is.. you will end up at the site, but it is still an outgoing link? Oct 26, 2011 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, 2011 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, 2011 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. Oct 26, 2011 at 15:20
  • @JoakimBörjesson Thank you for explain it to Moin :)
    – GusDeCooL
    Oct 26, 2011 at 15:35
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");
    }
}
0
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');

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');
0

You could use filter -

$("a").filter(function () {
    return this.indexOf('http://') > -1 && this.indexOf('gusdecool') == -1 
}).attr("target","_blank");  
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>

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.