Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript inline events syntax

Is there any reason to use one of the following more than the others:

<input type="button" value="b1" onclick="manageClick(this)" />
<input type="button" value="b2" onclick="manageClick(this);" />
<input type="button" value="b2" onclick="manageClick(this);return false;" />
<input type="button" value="b3" onclick="return manageClick(this);" />
<input type="button" value="b4" onclick="javascript:return manageClick(this);" />

And please do not spend your valuable time to tell me to use jQuery or attachEvent/addEventListener. It's not really the objective of my question.

like image 546
Mic Avatar asked Feb 04 '23 06:02

Mic


2 Answers

There's no difference at all between the first two, in this specific situation the semicolon is optional.

The third one will prevent any default action from occurring, which the first two won't.

The fourth will prevent the default action or not depending on the return value of manageClick.

The fifth one is incorrect.

(And wherever suitable, use attachEvent/addEventListener -- ducks and runs)

like image 179
T.J. Crowder Avatar answered Feb 05 '23 20:02

T.J. Crowder


<input type="button" value="b3" onclick="return manageClick(this);" />

edit Return is preferable in cases where you wish to control element behaviour, such as for <a> and <input type="submit">, so assuming this is the case, above is your answer, if not just omit the return and just go with onclick="manageClick(this);".

Also, have a look at http://crisp.tweakblogs.net/blog/313/the-useless-javascript-pseudo-protocol.html regarding the use of javascript:. ^_^

like image 28
kb. Avatar answered Feb 05 '23 21:02

kb.