I often tell everyone here to avoid examples of JavaScript on the Internet, because more often then not it’s incorrect. The same goes for most of the popular examples of how to cause a link, an A
tag more specfically, to open in a new window.
The most popular and incorrect way is using the target
attribute:
<a href="http://www.example.com/" target="_blank">Using Target</a>
The target
attribute was meant to direct content to load in a specific frame. In this case the keyword directs the browser to load the page in a new window, but with frames long dead and gone this little gem lives on as a reason people “can’t use HTML Strict.”:
The most common solution that people came up with this was to use JavaScript, but in some strange ways. Instead of opening the link directly, the page would go to an anchor and JavaScript would open the URL in a new window:
<a href="#" onclick="window.open('http://www.example.com/');">Using Onclick</a>
The HTML will validate, but if JavaScript is disabled the link won’t go anywhere, and it can’t be copied via a contextual menu. On top of that clicking on the link will cause the page to jump to the top, unless you add “return false;”:
<a href="#" onclick="window.open('http://www.example.com/'); return false;">Using Onclick</a>
Another approach to avoding the jump was to place JavaScript within the href
attribute:
<a href="javascript:window.open('http://www.example.com');">Using inline JavaScript</a>
While inline JavaScript has its novel uses, this isn’t one of them. This method doesn’t offer much over the previous one and can be complicated even further when a wrapper function is called instead:
<a href="javascript:wrapperfunction();">Using inline abstracted JavaScript</a>
The only way to fix the issue of JavaScript being disabled was to put the link back in the href attribute:
<a href="http://www.example.com/" onclick="window.open('http://www.example.com/'); return false;">Improved use of onclick</a>
Using “return false;” stops the link from executing, allowing the URL to be put back in the href
. This is the farthest I’ve seen any site go. it’s technically complete, but redundant. One last bit of JavaScript fixes that:
<a href="http://www.example.com/" onclick="window.open(this.href); return false;">Ideal use of onclick</a>
The redundancy is elimanted by using this.href
. “this
” refers to the current object in context, being the A tag. The “href
” references the A tags href property and the value (URL) contained within.
The end result is a small generic addition to any A
tag to make it open in a new window. The tag will pass HTML strict validation, “SEO” is preserved and if JavaScript is disabled everything keeps working.
Oh lordy, If target="_blank" is wrong….then I don't wanna be right.
🙂