New Window Links

Do you not like having to do target="_blank" all the time in your code to have a link open in a new tab? Or having to show clients how to do it in the Business Catalyst admin? Well with a small bit of jQuery you can have it all automated throughout your whole site.

Below is the really simple code that does all this external links for you.
This code requires you to use jQuery and it uses the methods not and on:

.on() - http://api.jquery.com/on/

.not() - http://api.jquery.com/not/


var developmentUrl = 'sitename.developmentdomain.com';
var secureUrl = 'sitename.worldsecuresystems.com';
var livesiteUrl = 'livesitedomain.com';

$("a[href^='http://'],a[href*='twitter.com']").not('.not-external').not("a[href^='"+livesiteUrl+"']").not("a[href^='"+developmentUrl+"']").not("a[href^='"+secureUrl+"']").not('a[rel^="external"]').on("click",function(e){
	e.preventDefault();
	window.open(this.href,'external');
});

So what is going on here?

1. Firstly you can see we set some variables up that are your sites Domains. You want to ensure the code knows not to open new tabs if your links go to your development url or your secure url and your live site.

2. The code simply says that for every link on the page and has a series of .not calls to tell it to not run in these cases. You have a class there you can add to links to prevent an external link from opening in a new tab and it will not do so for the URL's you specified as well. You can also add in your own.

You may have also noticed the twitter aspect, this is an example of how to prevent social media behavior from being interrupted as well.

3. e.preventDefault(); prevents the link running its normal behavior

4. window.open(this.href,'external'); Opens the link from the current anchor in a new window/tab.

Load more

Pinterest @Pretty_Pins

Twitter @Pretty_Thinks

Follow Us
Archive
    We're online
    Contact us
    Contact

    Let's Talk!
    Reach out, talk to us and a business representative will be in contact shortly.

    Captcha Image