In the original post I covered how to use jQuery to automatically make external links open in a new window. The method however was slightly flawed in my opinion since…
- It did not check form action attributes
- It assumed ANY link starting with “http[s]://” was external
Here is my new and improved method for making all external site links open in a new window. It now includes form tags, one less selector for secure and non-secure link urls, AND excludes any of those which link to an internal page where the full url may have been specified.
A quick breakdown…
- a[href*=”://“] and form[action*=”://“] matches the elements where a full url has been specified
- .not($(‘a[href*=”://’+location.host+'”]’)) excludes all matched items that include the current host (eg: http://www.robertmullaney.com/)
- finally we update the target attribute of the the remaining links open in a new window
Why this is important:
Once you have a user on your site, the worst thing you can do is send them away. Also, you will easily annoy them if all links open in new windows and cause them to leave anyhow. This way, only the links that pull them away from site site are opened in new windows. When they are done on the external sites, they close the browser and there your site remains.