Make all external links open in a new window/tab using jQuery

Alright, so I wanted to make a nice easy way to make all of the external links I post to open in a new tab. It just make sense to not facilitate users leaving your web site.

Step 1)
Target all of the anchor tags on the page when they are clicked.

Alright, so if that worked it means you did something right.

Step 2)
Get the url of the current page and split it down to the base URI for the page.

If that worked you will of course see your domain popup.

Step 3)
Check if the url is your own, if it isn’t add in the attribute of target=”_blank”

		var fullUrl = $(this).attr('href');
		var splitUrl = fullUrl.split("/");
		if((splitUrl[2] != '') && (splitUrl[2] != '')){

If you aren’t familiar with the usage of $(this), it is shorthand for the element clicked on. To finish, obviously replace my domain with your own, and voilĂ .

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>