Javascript objects

You,js

Assigning click handlers

A click handler can be assigned to a button or to any element in two ways: A1: assigning an onclick handler inline as an HTML attribute A2: assigning onclick handler in script B: using addEventListener at runtime in script to assign a handler

you can assign a function to onclick (old school, very limiting, not reccomended)

However if that is what you want to do, here are the dos anddonts:

A1: using onclick inline : extremely not reccomended

<button onclick ="someFunction();" id="abc">Click me</button>

A2: assigning the onclick property at runtime in the script section: You are in this situation passing a 'script block' or 'function block' to be stored against an attribute named onclick in this case you want to pass a value so you need to assign an anonymous function (or a named function defined inline) like

button=document.getElementById('abc');
parameter = 'some value';
button.onclick = function() {otherfunction(parameter)};

if you are cringing about how the parameter is scooped out from the global soup surrounding the function, you are not alone !

You can read more about 'javascript closures' .. Knowledge about closures may not end the cringe, but atleast the behaviour is now understood and thus it limits the damages.

In case the function you want to assign does NOT require a parameter you can use it directly

button.onclick = otherfunction;

Note that there is no parenthesis in this case

Now the most common noob error:

button.onclick = otherfunction(); // this doesn't work

This won't work because the function otherfunction() is invoked soon as it is parsed, thus instead of saying ...

"everytime the button is clicked, this is the code, I want you to call. save this code against the onclick handler and invoke it whenever the button gets clicked"

you are instead saying...

"everytime the button is clicked, the value returned by this function (run right now and find out the value), is what I want you to invoke. remember this value by assigning it to the onclick handler"

The value returned by the function is obviously not 'invocable' code, thus resulting in a runtime error and an event handler that just wont fire.

B: assigning a handler at runtime using the button.addEventListener('click', function) method instead