I have seen the following methods of putting JavaScript code in an <a>
tag:
function DoSomething() { ... return false; }
<a href="javascript:;" onClick="return DoSomething();">link</a>
<a href="javascript:DoSomething();">link</a>
<a href="javascript:void(0);" onClick="return DoSomething();">link</a>
<a href="#" onClick="return DoSomething();">link</a>
I understand the idea of trying to put a valid URL instead of just JavaScript code, just in case the user doesn't have JavaScript enabled. But for the purpose of this discussion, I need to assume JavaScript is enabled (they can't login without it).
I personally like option 2 as it allows you to see what's going to be run–especially useful when debuging where there are parameters being passed to the function. I have used it quite a bit and haven't found browser issues.
I have read that people recommend 4, because it gives the user a real link to follow, but really, # isn't "real". It will go absolutely no where.
Is there one that isn't support or is really bad, when you know the user has JavaScript enabled?
Related question: Href for JavaScript links: “#” or “javascript:void(0)”?.
I quite enjoy Matt Kruse's Javascript Best Practices article. In it, he states that using the href
section to execute JavaScript code is a bad idea. Even though you have stated that your users must have JavaScript enabled, there's no reason you can't have a simple HTML page that all your JavaScript links can point to for their href
section in the event that someone happens to turn off JavaScript after logging in. I would highly encourage you to still allow this fallback mechanism. Something like this will adhere to "best practices" and accomplish your goal:
<a href="javascript_required.html" onclick="doSomething(); return false;">go</a>