How to open external links & PDFs in a new window using jQuery

I'm not usually a fan of forcing new windows on users, be it for external sites or for viewing documents but there are cases in which your users may prefer it or clients may insist on it. If this is the case, then here's an easy way to do it with just a splash of jQuery.

If you're working with a Content Management System and others (especially non-developers) are updating content pages, this feature ensure the practice is maintained consistently and saves content editors from having to remember to add what otherwise would need to be additional markup to anchor tags that are required with other solutions. It also takes away the worry that they will inadvertently use target="_blank" which is, as we know, not standards-compliant.

Setting up jQuery

Make sure you have the latest version of jQuery and your common.js file in the <HEAD> section of your HTML page:

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js">
<script type="text/javascript" src="js/common.js">

Opening external links in a new window

To have all external links open automatically in a new browser window, simply add the following snippet to your common.js file:

// Opens all external links in a new window automatically	
$(document).ready(function(){
	$("a[href^='http']").attr('target','_blank');
});

Opening PDF documents in a new window

To do the same with PDFs, add the following snippet to your common.js file:

// Opens all PDFs in a new window automatically
$("a[href*=.pdf]").click(function(){
	window.open(this.href);
	return false;
});

Now when you mark up an anchor tag linking to an external page or an internal PDF, the new window for each will open by default. No fuss, no muss.

Stay well.

Please complete all fields to submit your comment.
Thanks. Your comment will be posted shortly.




This is your Captain speaking

Hi, my name's Fred and I'm a web designer & developer from Ottawa, Ontario. I specialize in front-end development and the user experience but also enjoy server-side development, SEO, social media and supporting my peers in the community.

Follow me on Twitter
Call me on Skype

Recent additions to the Community