Search code examples
javascripthtmlanchorhref

What is the right href value for a JavaScript anchor tag?


I usually have to bind a JavaScript function to an anchor-click event. That is easy using jquery or the onclick inline attribute.

But, my problem is that I never know what the best way to keep href empty is.

For instance:

  1. <a href="javascript:void(0)"> - It seems like a bit too much code for just being empty
  2. <a href=#> - If I don't want to move to another page, I must return false in the JavaScript call
  3. <a href> - This option breaks the cursor and hover style and the browser doesn't render it as a link
  4. <a> - idem

What is the best href value for empty anchors? I'm not interested to keep functionality without JavaScript


Solution

  • The right one is to use an empty a element href attribute and bind the click event in Javascript.

    For unobtrusive design, you should have a href attribute with a proper link (so those without Javascript can still use the site) and remove the attribute in Javascript, binding the click event.

    If you are simply using the a element as a target to bind the click event to, consider using a div or span instead.