JavaScript Onclick Return False

Like this blog? Consider exploring one of our sponsored banner ads...

Anywhere you put an onclick event with a javascript call, if you add return false then the default behavior (what would have happened without the onclick event) will be disregarded.

For example:

[html]Click Me[/html]

So now when a user clicks the link, the doSomething() function will fire off and the user will not go to http://www.nojs.com (unless they do not have javascript enabled).

To take it one step further, you can use the confirm function to force the user to confirm that they want to go to the link and then if they say ok then return true. For example:

[html]Click Me[/html]

And one final tidbit, soemthing I find irritating is when I use a link to AJAX something or toggle a div and then after I click the link and the onclick function fires off, the link is still selected. I know it doesn’t matter, whatever, here is a little hack you can do to keep this from happening. You basically “blur” the focus which is like unfocus. Here is a simple example:

[html]Toggle MyDiv[/html]

The preceding assumes that you are using prototype. If you are not using prototype then you need to start and you can get it and learn all about it here: Prototype


About this entry