Audio Visual Junkie

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! :)


Posted

in

by

Comments

9 responses to “Using JQuery to make all PDF links open in a new window”

  1. Kevin Avatar

    Awesome, just what I needed, thanks!

  2. Adrianne Avatar

    People say jquery is boring…