Saturday, September 17, 2005

<a href="javascript:..."> rant

Sometimes you want to do some special dynamic stuff on a webpage, by means of javascript. Well apperently a lot of people on this world think that only anchors (you know, thos <a href="..." /> thingies) are the thing for that. Well it's NOT. In fact it's the worst possible thing. Why? well, an anchor should contain a link to a new location. "javascript:..." is not a new location. Besides, since it's already used for dynamic stuff you should just use the "onclick" argument of pretty much every visible HTML tag. And now we ofcourse get: <a href="#" onclick="..." />. Well that's wrong too. Why? because you you create a link to nowhere. People (like me) often open a link in a new window\tab (middle mouse button is some browsers, or ctrl+click). Using a "#" or "javascript:" as link just breaks stuff like this and makes it annoying.

What is the right thing? Well, there are two options:

  1. For complete dynamic things that don't open new pages you should do something like <span onclick="javascriptFunctionCall()" >your text</span>, and maye make it more visible my means of CSS
  2. When you want to open a document in a special way (like a popup window with special properties) do something like this: <a href="linkToTheDocument" onclick="javascriptCallToOpenWindow('linkToTheDocument'); return false;">your text</a>. This way when a user normally clicks on the link it will call that javascript function with the url. If the user clicks on that link with the middle mouse button (or ctrl+click) it will simply open that link in the default behavior of the browser. The "return false" in the onclick makes sure the default behavior doesn't happen in case of the onclick event. This method gives you the best of both worlds and doesn't annoy users that link to middle click or don't have a javascript enabled browser.