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.

Paul Fleming
  • 24,238
  • 8
  • 76
  • 113
  • 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. – Bergi Jul 19 '12 at 11:52
  • possible duplicate of [Javascript onclick return functionality](http://stackoverflow.com/questions/7814949/javascript-onclick-return-functionality) – Jeremy Jul 19 '12 at 18:59

3 Answers3

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().

Paul Fleming
  • 24,238
  • 8
  • 76
  • 113
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 -->

Community
  • 1
  • 1
Filip Roséen - refp
  • 62,493
  • 20
  • 150
  • 196
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.

Ankit
  • 3,083
  • 7
  • 35
  • 59