Opening external links in a new window using jQuery

Using external for rel attribute on a link, you can specify that the link is outside of the current site. This attribute is commonly used for SEO and styling options. And to open a link in a new window when user clicks it you can use target attribute. What if you wanted all external links to open in a new window? jQuery is the answer.

To easily add target blank attribute to all external links you can use attribute selectors that come with jQuery:

 jQuery(function() { jQuery('a[rel~=external]').attr('target', '_blank'); }); 

This simple line of code adds target="_blank" attribute to all external links on your site. However, this should be done when the DOM is loaded. So we need to wrap this code with the document ready function like this:

<script type="text/javascript">
/* <![CDATA[ */
jQuery(document).ready(function() {
	//External links 
	jQuery(function() { jQuery('a[rel~=external]').attr('target', '_blank'); }); 
});
/* ]]> */
</script>

If you want this trick for your wordpress site, put this code in footer.php in your theme just before </body> tag. This way all your rel="external" links will open in a new window.

Hope you like this simple trick.

Related Posts

NS Weight Release

WP-Backgrounds Lite by InoPlugs Web Design and Juwelier Schönmann 1010 Wien