Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery add target="_blank" for outgoing link

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> 
like image 374
GusDeCooL Avatar asked Oct 26 '11 10:10

GusDeCooL


People also ask

How do you add a target _blank to a URL?

Conclusion. You can use the target="_blank" attribute if you want your users to click on a link that opens up a new browser tab. The target="_blank" attribute is used inside the opening anchor tag like this.

What happens if you add target _blank to a link?

a target=”_blank” Open in New Browser Tab (or Window) The target attribute specifies where the linked document will open when the link is clicked. The default is the current window. If target="_blank" , the linked document will open in a new tab or (on older browsers) a new window.

Is Target _blank deprecated?

It looks like target="_blank" is still alright. It is listed as a browsing context keyword in the latest HTML5 draft.

What is target _blank in a href?

Description. _blank. Opens the linked document in a new window or tab. _self. Opens the linked document in the same frame as it was clicked (this is default)


2 Answers

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

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

like image 107
Moin Zaman Avatar answered Sep 28 '22 11:09

Moin Zaman


$('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.

like image 20
Ryan Doom Avatar answered Sep 28 '22 13:09

Ryan Doom