How to Write Gracefully Degrading Javascript onClick Event Handlers
There a couple of ways to invoke javascript events via the onClick handler.
Approach #1
The one I see most often is this:
<a href="#" onClick="someFunction();">Click me. I know you want to.</a>
This is my least preferred. Why? Because depending on what the function actually does, there’s a good chance that what will happen is that someFunction will be called and the screen will then shift to the top of the document. This I find just annoying.
Approach #2
An improvement on that first case is this:
<a href="#" onClick="someFunction(); return false;">Click me. I know you want to.</a>
By returning false inside onClick you execute the javascript, but the screen won’t scroll to the top of the document. This is better. But, it’s still not perfect. The problem with this is that it doesn’t degrade well into browsers with javascript turned off. If javascript is disabled in the browser, clicking on the link will just pop the user to the top of the page and leave them there. This is unexpected and it’s not helpful to them in any way.
Approach #3
The best overall approach is this:
<a href="/javascript_required.html" onClick="someFunction(); return false;">Click me. I know you want to.</a>
In the event that the user has javascript disabled in their browser, they will be taken to a page (/javascript_required.html) where you can explain to them that they have javascript turned off and that it’s needed for certain functionality to work. In the event that their browser has javascript turned on, then they will see whatever behaviour you intend. It’s the perfect solution!
One note on these approaches: The second case is my preferred technique while developing and debugging applications. Without the "#" as the href, should your event handler throw an exception or otherwise run into trouble, your browser will just go to the url specified in the href attribute. If this takes you to another page you won’t get to see what went wrong. So, leave the href attribute as "#" while debugging. Switch it to something akin to "/javascript_required.html" when going to production.
