Thank you. Your comment will be posted following moderation.
Please complete the form to post your comment.
{ a resource for web designers & developers }
RSS feed Twitter Flickr YouTube

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.





Set Phasers on Fun!

Skyrocket Labs is a resource for beginner to advanced web designers & developers, offering original jQuery scripts & design tools, insight into best practices and industry trends and, more importantly, dedicated to celebrating and exchanging with the vast and amazing talent in the designer/developer community. It's about learning, sharing, growing and having a blast.

In the Community

CSS Globe Speckyboy Usability Post Peter Hinton Design Blue Awesome AEXT Smashing Magazine Six Revisions Janko at Warp Speed