← Back to blog home

Simple jQuery script to automatically open external links in new window

05 Jun

Often times on sites it's useful to automatically have any external link open in a new window. This is a very simple solution that just overrides any link that starts with http:// or https:// and forces them to open in a new window. There are obviously other ways to accomplish this but this is the most simple method. This method consists of a simple jQuery function and forces external links to open in a new window. This is useful for any site with unpredictable content when you know you want external links to open in a new window.

$("a[href^='http://'],a[href^='https://']").click(function(){
    window.open($(this).attr('href'));
    return false;
});

The above code can be problematic if your site uses full urls. For example my site has full urls in the navigation (eg http://itslennysfault.com/about) so with the code above those links would open in a new window. To avoid this use the following code and update "goodDomain" to your site's url.

    $("a[href^='http://'],a[href^='https://']").click(function(){
    	var myHref=$(this).attr('href');
    	var goodDomain="http://itslennysfault.com";
    	if(myHref.toLowerCase().substr(0,goodDomain.length)==goodDomain)
    		return true;
    	window.open(myHref);
    	return false;
    });

Obviously, either code should be placed inside a wrapper and loaded after the DOM is ready.

 
1 Comment

Posted in Quick Tips

 

Leave a Reply

Notify me of future comments

(I don't spam or share your e-mail. Unsubscribing is as easy as clicking the "unsubscribe" link in the notifications)
 

 

 
  1. Jordan

    June 14, 2011 at 6:16 am

    Thank you, this was really useful :) my advertisements now show in a new window rather than loosing me traffic.