Tuesday, February 22, 2011

Who's afraid of javascript:void()?

Very few people, apparently. It's used all over the place. In fact I had been using that old chestnut, javascript:void(0), for quite some time to implement popups on my blog. I'd read somewhere that this is considered bad coding practice, but I didn't know exactly why. So, kids, if you take away nothing else from this article--learn this worldly lesson: you can find the solution to just about any coding issue by searching on Google.

You can search, but the results usually answer your question obliquely. After reading a few blog posts, I finally found out why you should avoid void(). (In the interest of full disclosure, the clearest of these articles was Javascript href Voids and More.)

There are good parts and bad parts to JavaScript; it is in fact a full-fledged, object-oriented language, but it has features that allow you to write code sloppier than a 4-year-old plowing through a Big Mac. One of these pitfalls is using void() in a link, because it's an easy hack. The technical reason to avoid void(0) is that it can produce indeterminate results on some browsers, or when Javascript is disabled on the browser.

So let us say that we'd like to implement a popup that provides the English translation of a German word. The following script uses void(0) to generate a popup saying "German for 'so-called'" when you put the mouse over the word "sogenannte:"

<a href="javascript:void(0)" title="German for 'so-called'"><em>sogenannte</em></a>

Try it by positioning the mouse over the word below:

sogenannte

Here's the preferred method: Instead of using void(), set href to "#", which is a kind of shorthand meaning "this page." Handle the onmouseover event by returning false. Also disable clicking on the link by making the onclick event return false:

<a href="#" onclick="return false;" onmouseover="return false" title="German for 'so-called'"></em>sogenannte</em></a>

Now position the mouse over the following link:

sogenannte

Using '#' as a substitute for the void() function is supported by all major browsers and is considered to be the correct method. If you're concerned about how this would behave when Javascript is disabled in the browser, you can replace '#' with a valid URL; a good choice is to insert the URL of the same page on which the link resides. The user will see a refresh, but will stay on the same page.