advice + opinion

recent entries

Can’t Touch This
posted Mar 7, 2013 10:37am
Wufoo Textarea Form Fix Voodoo
posted Dec 14, 2011 4:37pm
Anti-Social Networking
posted Oct 16, 2011 4:51pm
Opening External Links and Files in New Window
posted Mar 18, 2011 2:09pm
Intro to Web: Where to Start
posted Oct 27, 2010 5:17pm

Opening External Links and Files in New Window

posted Mar 18, 2011 2:09pmdevelopment tips + tricks

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.