How to open external links & PDFs in a new window using jQuery
January 31, 2010 jQuery Tutorials
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.













When I use this, it opens internal links in a new window as well, not just external links. Is there a trick to get internal links to open in the same window?
Posted: February 5, 2010
Internal links will open in the same window by default but if you're encountering this issue my first guess would be that your internal links aren't relative. If you have a link so I can take a peek that would be great. You can also email me if you need. Cheers.
Posted: February 5, 2010