Technology

Using JQuery to make all PDF links open in a new window

Sometimes it can be really annoying for the user to open a PDF file in the same window, and sometimes you might find yourself working on an existing website, faced with the insurmountable task of making sure all PDF links open in a new window.

Just like today.

Forget about manual editing, it will only take too long.

Forget about search and replace, you might mess up the code.

JQuery to the rescue!

See my code below:

$("a[href*=.pdf]").click(function(){
	window.open(this.href);
	return false;
});

Alternatively, you can apply the target=”_self” attribute instead:

$("a[href*=.pdf]").click(function(){
	$(this).attr({"target":"_self"});
	return false;
});

Viola! With Just four lines of code, you now open all pdf links in a new window! Thanks to JQuery’s awesome element matching engine and attribute pattern recognition, you can actually modify the code to apply the same behavior to any link, as long as the text can be found anywhere within the href attribute.

Have fun! :)