Opening External Links and Files in New Window

posted Mar 18, 2011 9:09pm

I needed to automate a client's site so that links that go to other sites open in a new window. Simple enough. However, this needed to also work for secure (https://) links and any linked PDF files too.

I’d found jQuery scripts that did one or the other, but wanted something I could add onto if need be. So this:

jQuery("a[href*='http://']:not([href*='"+location.hostname+"']),
[href*='https://']:not([href*='"+location.hostname+"']),
a[href*='.pdf']")
.attr("target","_blank"); 

…seemed to cover all the bases. The third line, which handles the PDF files, can be repeated for other file types buy replacing the appropriate file extension. Just remember to add a comma after each line except the last.

Hope that helps someone else.