Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

Mar 7, 2011

Stopping link onclick from causing the browser to jump around

Often we may use links to enact Javascript functions in this fashion:

<a href=”#” onclick=”dosomething();”>click me</a>

While this works, the browser thinks you clicked on an anchor link and may "jump" the browser view port to the top left corner of the content.

A common way to work around this is to have the method dosomething(); return false. By doing so the browser should short-circuit the event model and not enact the href call. I say should because everyone's favorite browser - IE6 - does not. IE6 does not pass the event to the function, calling false does not stop the event propagation.

This can work:

<a href=”javascript:;” onclick=”dosomething();”>click me</a>

But it may cause problems. This call propagates an event call specific to IE and can break certain functionality.

A safer way is the following:

<a href=”#” onclick=”dosomething(); event.returnValue=false; return false;”>click me</a>

This works perfectly. The event will not propagate and the href action will not occur.

I wish I could give credit to the individual who pointed this out to me, but I can't find the link any more.

Props to Web Developers Journal for providing me with the original concept.