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.
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).
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")]);
});
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With