Recent Posts

Showing posts with label link. Show all posts
Showing posts with label link. Show all posts

HTML Best Practices: HREF attribute for JavaScript link # or javascript:void(0)

<a href="#" onclick="myJsFunc();">Run JavaScript Code</a>
<a href="javascript:void(0)" onclick="myJsFunc();">Run JavaScript Code</a>
Neither is the correct way to build a JavaScript link.

If you can have an actual URL that makes sense use that as the HREF. The onclick won't fire if someone middle-clicks on your link to open a new tab or if they have JavaScript disabled.

If that is not possible, then you should at least inject the anchor tag into the document with JavaScript and the appropriate click event handlers.

I realize this isn't always possible, but in my opinion it should be striven for in developing any public website.

Check out Unobtrusive JavaScript and Progressive enhancement (both Wikipedia).