JavaScript

How to open a link in a new window using JavaScript…the right way.

First, the wrong way:

<a href="#" onclick="window.open('http://www.digitalmachina.com/');">the wrong way</a>

So what’s wrong with the above code?

  1. Since the href attribute contains a hash “#” character, and not an actual URL, search engines will not be able to follow the link. Search Engine Optimization (SEO) is extremely important, so this should be reason enough.
  2. If the user is not using a JavaScript enabled browser, the link will not work at all.
  3. Users will not be able to use any of the useful browser features available from the context menu for links including: Open Link in New Window/Tab, Bookmark This Link, Save Link As, Send Link or Copy Link Location. Breaking the functionality of a users browser is never a good thing.
  4. When the link is clicked on, the browser will append the hash character contained in the href attribute to the end of the URL in the address bar. This action by the browser screws up the user’s browsing history. Also, if the user feels like refreshing the page by hitting enter in the address bar, it won’t work. They’ll have to manually remove the hash character first.

Now, the right way:

<a href="http://www.digitalmachina.com/" onclick="window.open('http://www.digitalmachina.com/'); return false;" target="_blank">the right way</a>

What’s different?

  1. The href attribute contains the real URL of the linked page. This is SEO friendly, and doesn’t break any functionality of the user’s browser.
  2. The value of the onclick attribute ends with “return false;”. By adding this piece to the end of the string, it tells the browser not to follow the link contained in the href attribute. This is required now that the href actually contains a valid URL.
  3. Finally, if the user is not using a JavaScript enabled browser, the link will still work.

Tags: ,

Thursday, March 12th, 2009 Programming 2 Comments