Friday, March 2, 2012

Don't use # to create empty links

An empty link is a <a> tag that doesn’t link to anywhere. Oftentimes, we have these links where we want to ignore the href attribute and customize the behavior for the click events. To make an empty link, usually, we put a “#” in the href attribute, like this:

<a href=”#”>link</a>

This approach is simple, however, the “#” href introduced two issues:

1. It creates an entry in browser history whenever users click on the link.

2. (This is caused by the first issue) If the link is in the middle of a page, after clicking the link, users will be brought back to the top of the page.

A # in a href attribute points to an anchor. If the anchor name is empty, it refers to the top of the current page itself. When user clicks on such # link, browsers treat # as a normal navigation, and put it to the history stack. When users click on the back button, they expect a previous page, however, what they will see is the current page again, because the # is at the top of the history stack, and it points to the current page. If users click the # link multiple times, a same amount of # entries will be put to the history stack, and users have to click back button several times in order to go back to the real previous page. This behavior certainly introduces confusions to users.

Since browser treats # as a normal navigation, and # refers to the top of the current page, when users click on the # links, browser will display the current page with the vertical scroll bar being reset to the top. User will lose their scrolling positions. This will be a big problem for long pages.

The correct way to create an empty link is:

<a href=”javascript:void(0);”>link</a>

This will make browser ignore the href attribute, and won’t introduce a new entry in browser history.

5 comments:

  1. Thanks. It is nice to see that bowser do nothing. Really:)

    ReplyDelete
  2. Thank you. Very helpful

    ReplyDelete
  3. I know this is an old post, but I´m curious about one thing..
    Normally I use href="javascript:;" when I need to make an "empty" link.
    What is the difference between "javascript:;" and "javascript:void(0);" if any?

    ReplyDelete
  4. I had deleted a line inside a href with nothing else and it opened my File Explorer, to the left, in a minimized screen
    I tested this in an open notepad-saved HTML (test.html) and clicked the link from my browser. How did this happen?

    ReplyDelete
    Replies
    1. it would be typed as

      less than
      a
      href
      greater than
      This post does not allow for bad syntax or errors so I cannot type it out

      Delete