Open all external links in new window or tab using jquery

In this programming tutorial we will learn how to open all external links in new window or tab using jquery. External links should be open in new window or tab because we should not lost the focus of user from our website if he clicks the external link. We all know that to open a link in a new window, we have to set the target attribute as '_blank' in our HTML link tag. But this process is very time consuming if we have huge number of external links in our page. To get rid of this problem just have a look over following code snippet.

Open all external links in new window using jquery
Put this script just before <body> tag
<script language="javascript" type="text/javascript">
$("a[href*='http://']:not([href*='"+location.hostname.replace("www.","")+"'])").each(function() {
$(this).attr('target', "_blank");
    });
</script>
That's it. And if you want to add css class to external hyperlinks then use this code
<script language="javascript" type="text/javascript">
$("a[href*='http://']:not([href*='"+location.hostname.replace("www.","")+"'])").each(function() {
$(this).addClass('externalLinkClass').attr('target', "_blank");
    });
</script>

And here is the css class
.externalLinkClass {
    color:red;
    font-weight:bold;
    text-decoration:none;
}

So that's it.
I Love your feedback.

0 comments: