Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the effect of adding 'return false' to a click event listener?

Many times I've seen links like these in HTML pages:

<a href='#' onclick='someFunc(3.1415926); return false;'>Click here !</a> 

What's the effect of the return false in there?

Also, I don't usually see that in buttons.

Is this specified anywhere? In some spec in w3.org?

like image 326
Leonel Avatar asked Sep 24 '08 18:09

Leonel


People also ask

What does onclick return false do?

If there is a return false statement then there in an event listener for that alert message, it may correspond to not executing the default set of instructions . The return value of the event handler is used to determine if the default (desired) browser behavior should take place or not.

What happens when the onclick event handler for a radio button returns false?

Selecting a radio button will trigger an onclick event. If your event handler returns false, Internet Explorer will not change the state of any radio buttons.

What is the meaning of return false in JavaScript?

You use return false to prevent something from happening. So if you have a script running on submit then return false will prevent the submit from working.

What means return false?

1 : an incorrect report false returns on an income-tax blank. 2 : an untrue return made to a legal process by the officer to whom it was delivered for execution.


2 Answers

The return value of an event handler determines whether or not the default browser behaviour should take place as well. In the case of clicking on links, this would be following the link, but the difference is most noticeable in form submit handlers, where you can cancel a form submission if the user has made a mistake entering the information.

I don't believe there is a W3C specification for this. All the ancient JavaScript interfaces like this have been given the nickname "DOM 0", and are mostly unspecified. You may have some luck reading old Netscape 2 documentation.

The modern way of achieving this effect is to call event.preventDefault(), and this is specified in the DOM 2 Events specification.

like image 112
Jim Avatar answered Oct 19 '22 02:10

Jim


You can see the difference with the following example:

<a href="http://www.google.co.uk/" onclick="return (confirm('Follow this link?'))">Google</a> 

Clicking "Okay" returns true, and the link is followed. Clicking "Cancel" returns false and doesn't follow the link. If javascript is disabled the link is followed normally.

like image 24
HoboBen Avatar answered Oct 19 '22 02:10

HoboBen