What is the difference between the different methods of putting JavaScript code in an <a>? What is the difference between the different methods of putting JavaScript code in an <a>? javascript javascript

What is the difference between the different methods of putting JavaScript code in an <a>?


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.


You forgot another method:

5: <a href="#" id="myLink">Link</a>

With the JavaScript code:

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 JavaScript code. It keeps all the JavaScript code 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.