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)”?.
JavaScript in head: A JavaScript function is placed inside the head section of an HTML page and the function is invoked when a button is clicked. JavaScript in body: A JavaScript function is placed inside the body section of an HTML page and the function is invoked when a button is clicked.
The best practice is to put JavaScript <script> tags just before the closing </body> tag rather than in the <head> section of your HTML. The reason for this is that HTML loads from top to bottom. The head loads first, then the body, and then everything inside the body.
No difference in JavaScript. The only requisite is that the last quotation mark matches the first quotation mark. In other languages they may have different applications but in JavaScript they are exactly the same.
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>
Why would you do this when you can use addEventListener
/attachEvent
? If there is no href
-equivalent, don't use an <a>
, use a <button>
and style it accordingly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With