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.
views:
1348answers:
6you forgot another method:
5: <a href="#" id="myLink">Link</a>
with the javascript:
document.getElementById('myLink').onclick = function() {
// do stuff
};
I can't comment on which of the options has the best support or which is semantically the best, but I'll just say that I much prefer this style because it separates your content from your JS. It keeps all the Javascript together, which is much easier to maintain (especially if you are applying this to many links), and you can even put it in an external file which can then be packed to reduce filesize and cached by client browsers.
<a href="#" onClick="DoSomething(); return false;">link</a>
I will do this, or:
<a href="#" id = "Link">link</a>
(document.getElementById("Link")).onclick = function() { DoSomething(); return false; };
Depending on the situation. For larger apps, the second one is best because then it consolidates your event code.
I quite enjoy Matt Kruse's Javascript Best Practices article. In it, he states that using the href
section to execute javascript 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>
Method #2 has a syntax error in FF3 and IE7. I prefer methods #1 and #3, because #4 dirty the URI with '#' although causes less typing... Obviously, as noted by other responses, the best solution is separate html from event handling.
What Not To Do
<a href="javascript:doSomething()">link</a>
<a href="#" onClick="doSomething()">link</a>
<a href="#" onClick="javascript:doSomething();">link</a>
<a href="#" onClick="javascript:doSomething(); return false;">link</a>