Wednesday, March 14, 2007

Issues with javascript:void(0)

There are plenty of occasions when coding JavaScript events where you simply need to call a function, for which an entire event registration model is too lengthy. The most commonly used method is to bind your event to an anchor link. The user clicks and the onclick event is fired, calling a reference to a function.

Because the user isn’t actually visiting a URL, something has to be done with the href attribute.
There are 2 options:
  • Use href="#"

Not finding a name (anchor link) after the pound, the browser “kicks” the user to the top of the current page, losing the location in the document.

  • Use href="javascript:void(0);"

Lets go with second option:

<a onclick="someMethod('userControlName')" href="javascript:void(0);">Click Here</a>

I tried to load user control in someMethod('userControlName'). It was working in IE7 and Firefox but not on IE6.

After investing into it a little bit, I found out a simple solution:

><a onclick="someMethod('userControlName'); return false;" href="javascript:void(0);">Click Here</a>

“return false” stops any other action after the person has finished the onClick action. This prevented event bubbling action (For excellent article on Event bubbling, see )

No comments: