Friday, 5 January 2007

Preventing a page from reloading when using onClick event in a HREF

The hyperlink is often used instead of a button to run a javascript method using the onClick() event of a link with a value of "#"

<a href="#" onclick="someMethod();">This Does Something</a>

However this also reloads the page, which may result in loss of some changes performed by someMethod(). For example, if someMethod() changes the display of page elements -- a page reload will result in the page looking like it was *before* someMethod() was called.

To prevent this, it's good practice to return false to the onclick event, similar to the way we return false to onsubmit event in a form, where we don't want the form to submit.
so we either:

1. Modify someMethod() to return a value of false and change our HREF to:
<a href="#" onclick="return someMethod();">This Does Something</a>

2. Or add a return false; after calling someMethod(), like so:
<a href="#" onclick="someMethod(); return false;">This Does Something</a>


No comments: