Posted on 02 Mar 2001
by Jeff Howden (Jeff Howden)
Rated 4.24 (Ratings: 18)
- More articles in Code
I'm not sure why the code I'm looking at has a
return here? I took the
return out in a similar onclick event and it still worked fine.
The function the event handler was calling may not have been written to return a value.
In order to understand why this is important though, I want to talk about the
return statement in an event handler and what that accomplishes. There are some event handlers that can be cancelled. Canceling an event effectively renders the default behavior of the tag the event handler is attached to useless. Take the following as an example:
When the behavior is run in your web browser you end up with something like this link that does absolutely nothing.
You can click on the link all day long and go nowhere. The statement
return false is canceling the default behavior of the
, which is to navigate to the value of the href attribute. This is a really simple example, but suffice to say, so long as the
return statement is passing a boolean value (
false), you can affect the behavior of the event handlers they are attached to.
To take this into more worldly, practical example, let's consider a link to a rather large file. Let's say we want to be able to warn the user when they click on that link and ask them if they really want to download that file. We can do this using the
Let's look at an intermediary example to see how that works before moving on to the final solution. This example will call the
confirm() method and assign the value of the user's action (whether they click the OK button, returning a value of
true from the
confirm() method or they click the close or cancel button returning a value of
false from the
confirm() method) to a variable. We will then use an
alert() dialogue to display the value of this variable.
When the HTML is run in your web browser you end up with something like this link that when clicked displays first a
confirm() dialogue and then an
alert() dialogue containing the boolean returned by the
return statement within the event handler, we can alter the behavior of the <a> tag depending on what button the user clicks. All we have to do is complete the
return statement in the
onClick event handler with a boolean which will be stored from
confirm() dialogue in the
When the above is run, the following is produced:
return statement is looking for a boolean value (
false, the same kind of value the
confirm() dialogue returns). Knowing this we can use the
confirm() dialogue (and consequently the value it will return) as the boolean in the
return statement for the event handler.
I hope that the use of the
return statement makes a little more sense now.