5

What is the difference between:

<div onclick="return function()"></div>

vs

<div onclick="function()"></div> 

They seem to be doing the same thing for me and I am not sure which one to use.

2
  • 3
    Try to not use HTML event attributes at all. Get familiar with the traditional event model (pure js), and you'll understand what it means to return values from handlers. Commented Jul 19, 2012 at 11:52
  • possible duplicate of Javascript onclick return functionality Commented Jul 19, 2012 at 18:59

3 Answers 3

10

Take for example <form onsubmit="return validate();">... The submit will be cancelled if validate() returns false.

With <form onsubmit="validate();">... The submit will continue regardless of the return value of validate().

Sign up to request clarification or add additional context in comments.

Comments

2

Explanation in words..

One will return the value to the element which the attribute resides in, the other will not.

When you use return function () the default click-method of the element will only be executed if function () evaluates to a value that implicitly is converted to true.

If it yields false the evaluation of the click-event will halt after running the onclick-property.


In case of onclick="function ()" the default click-propery of the element will always be executed, no matter what the function returns.


Example snippets with detailed information of what is happening..

function some_func () { return false; }

<a href="http://google.com" onclick="return some_func()">
  link #1
</a> <!-- user will never end up at google -->

if javascript is enabled in the browser, of course..

<a href="http://google.com" onclick="some_func()">
  link #1
</a> <!-- user will always end up at google -->

Comments

1

There is a difference, if you write return, it will check if the return is true or false and will only take action if return is true. otherwise it will just process.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.