I'm not sure if this has been asked before because I don't know what it's called.
But why wouldn't a method like this work? Below is just a general example
<script>
document.getElementById('main_div').onclick=clickie(argument1,argument2);
function clickie(parameter1,parameter2){
//code here
}
</script>
The code above would work fine if the event handler was assigned without parameters, but with parameters, it doesn't work. I think I read online that to overcome this problem, you could use closures. I'm assuming it's because of the parentheses ( ) that is calling the function immediately instead of assigning it to the event?
To bind an event to a element, you need to use either the
attachEvent
oraddEventListener
method. For example.A function name followed by parentheses is interpreted as a function call or the start of a function declaration. The a onclick property needs to be set to a function object. A function declaration is a statement, and is not itself a function. It doesn't return a reference to the function. Instead it has the side effect of creating a variable in the global scope that refers to a new function object.
creates a global variable named clickie that refers to a function object. One could then assign that object as an event handler like so:
element.onclick = clickie;
. An anonymous function declaration (often confused with a closure; for the difference see Closure vs Anonymous function (difference?)) does return a function object and can be assigned to a property as an event handler, as follows:But this doesn't work:
Why? Because
function clickie(event) { return true;}
is a statement, not a function. It doesn't return anything. So there is nothing to be assigned to the onclick property. Hope this helps.When you say onClick = function() {...} you are registering your function with some internal JavaScript library. So when the "click" happens, that library invokes your function.
Now imagine you're the author of that library and someone registered their function with it. How would you know how many parameters to pass to the function? How would you know know what kind of parameters to pass in?
This means to invoke the function and return its return value.
This simply is a reference to the function (doesn't invoke/execute it)
Because you're calling the function immediately and returning the result, not referencing it.
When adding the parenthesis you call the function and pass the result back to onclick
so it's actually equal to writing
which is not what you want, you want
but then you can't pass arguments, so to do that you could use an anonymous function as well
or use
bind
It is however generally better to use
addEventListener
to attach event listeners, but the same principle applies, it's either (without arguments)or
bind
or the anonymous function to pass arguments etc.The easiest way is: