Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

syntax difference in javascript function calling?

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.

like image 846
user1537688 Avatar asked Jul 19 '12 11:07

user1537688


2 Answers

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

like image 99
Paul Fleming Avatar answered Sep 20 '22 16:09

Paul Fleming


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 -->

like image 40
Filip Roséen - refp Avatar answered Sep 18 '22 16:09

Filip Roséen - refp