JavaScript in <a> tags: # vs javascript:void(0)

Often times when we get a set of html templates from a designer, we tend to see a lot of this:

image

Moreover, we tend to leave these href="#" attributes in place when we add onclick events to these tags so that we don't have to add an CSS to it in order for the anchor to behave like a normal anchor.

 

We end up with stuff that looks like one of these:

image

So why is this troublesome?

Well, imagine one of these links on a page or element that was scrolled down or to the side - unless you had returned false in the click event, the href="#" is going to behave like it should and scroll to the top left of the scrolled element. 

Oops.  Probably not what we intended for the user.

Easy fix?  Do one the following:

image

The first tag uses the void() method and thus has no affect on the scroll position; even if the myClickHandler() event fails, everything will stay put in terms of the scroll.

The second tag places the event handler directly in the href attribute.  This works, but it isn't very useful if you want to able to change the onclick event programmatically, or to do other client side event binding (using something like jQuery), which rocks.

The third line also will avoid the scroll-jump issue - but only if the myClickHandler() method doesn't fail! Even though we don't write code with intention of it failing, having a page potentially scroll-jump all over the place is not a good example of the kind of graceful degradation that we should be incorporating into our pages....

 

Hope this helps a bit - joel.

1 Comment

  • Thank you. It's nice to read somebody with an unbiased position on javascript:void(0). Some folks think it's a sin. Get over it. When IE catches up to standards we'll talk.

Comments have been disabled for this content.