How to Open All External Links in a New Window/Tabs by using jquery

Do you ever know the way to open an external link in a new windows or tabs is one of The Top Ten Web Design Mistakes of 1999?

Opening up new browser windows is like a vacuum cleaner sales person who starts a visit by emptying an ash tray on the customer’s carpet. Don’t pollute my screen with any more windows, thanks (particularly since current operating systems have miserable window management).
Designers open new browser windows on the theory that it keeps users on their site. But even disregarding the user-hostile message implied in taking over the user’s machine, the strategy is self-defeating since it disables the Back button which is the normal way users return to previous sites.

I discovered right away is that the <a> tag does not allow the target attribute in XHTML Strict (nor does it in HTML Strict).

External Links
Open external links

However, the behavior of <a target="_blank"'> can be replicated in XHTML Strict with semantic markup and scripting.
If you know anything about attribute selectors, that should look familiar to you. Basically, it is saying, apply the attribute target="_blank" to all links that begin with http. I have written a few lines of jQuery code that will convert all external links (i.e. links that begin with http) to links opening up in a new window by injecting the <a target="_blank"'> behind the screens. I’m going to make sure you have jQuery active on your site, you can do this easily in WordPress, since it’s bundled with the latest installations.

//	Open external links in new windows using jquery
	$('a[href^="http://"]').filter(function() {
        return this.hostname && this.hostname !== location.hostname;
    }).attr('target', '_blank');

Really easy, really powerful, problem solved.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.