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

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

5 Comments

nope, please see my comment for Joakim for the explanation :)
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.
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.
This will not include https sites, you should probably just use $('a[href^="http"]').not('a[href*=gusdecool]').attr('target','_blank');
I needed to set "gusdecool" into single or double quotes to make the code work.
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 Comment

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?
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 Comments

Nice jQuery selector! This should get voted above the selected correct answer as it is the best/fastest solution.
You might want to add "s? Because I'm getting unrecognized expressions.
Using these jQuery selectors can affect javascript performance.
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 Comment

This is the best answer to me, since totally agnostic (i.e. not hard-written stuffs) and fully explicit. +1
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

Comments

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 Comment

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).
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 Comment

It would be great if you could provide a short explanation of your code!
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.

Comments

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 Comments

well kind of it is.. you will end up at the site, but it is still an outgoing link?
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 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?
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.
@JoakimBörjesson Thank you for explain it to Moin :)
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"); } } 

Comments

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

Comments

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

Comments

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

Comments

0

You could use filter -

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

Comments

0

Try:

$('a[href^="http://"]') .not('a[href*='+ location.hostname +']') .attr('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.