Say you are developing a page and you want a link to fire a JavaScript function? (See the bookmark link below). What do you do?
If you are like most developers, you want to fire the JavaScript function with the onclick event, like onclick="myFunction();". You also know that if you put href="#" in the hyperlink, the page will refresh when the link is clicked, because the hash character is telling the user's browser to reload the page and go to the bookmark following the hash character, which in this case does not exist. The result? An annoying flash and maybe a click sound as the page reloads.
So, we all learned to do a couple of cheats. The most propionate is <a href="javascript:void(0)" onclick="myFunction();">Click Here</a>, another is <a href="javascript:;" onclick="myFunction();">Click Here</a> and yet another is <a href="javascript:myFunction();">Click Here</a>.
This is bad for a number of reasons, not the least of which is accessibility, but if you don't care about that maybe you'll care about the SEO penalty and unnecessary 404 errors in your logs when non JavaScript enabled browsers hit the link.
There are a number of alternatives which are much better.
1. If the function performed by the JavaScript function can be handled on a plain HTML page useable by a non JavaScript enabled browser, then write that page and use its URL in the href. You can still use the onclick event to fire the JavaScript version for JavaScript enabled browsers and you can stop JavaScript enabled browsers from going to the URL in the href, (see #3 below).
2. If the function can not be performed by another page, maybe you would be better off using a button. Buttons are made for calling functions, hyperlinks are not. You can always use CSS to style the button like a link.
3. If you insist on using the anchor tag, go ahead and put the hash mark in the href, but change your onclick handler and the JavaScript function to return false, which over rides the default hyperlink behavior an won't cause the page refresh in IE with JavaScript enabled. For DOM 2 event handling browsers, events go through a capture phase before bubbling up, so we simply add an event listener on the body for click in the capture mode and check if the target was an anchor; if so we prevent the default behavior.
<a href="comments.html" onclick="return showCommentForm();">
<a title="A link to the contact form" href="../contact.asp" onclick="return showForm();">Click to contact me</a>
And for DOM 2 browsers we add:
<body onload="getClick()"...>
function getClick() {
if (document.body.addEventListener) {
document.body.addEventListener("click", clickHandler, true);
}
}
function clickHandler(e) {
if (e.target.tagName=='A') {
e.preventDefault();
}
}