I know this question might be silly just would like to know, and I am not sure whether the topic matches to my current asking. But still thought to ask it.
<button id="Clk">Click on me</button>
document.getElementById("Clk").onclick = function(){alert("firedme!")}
document.getElementById("Clk").onclick = fire();
function fire(){alert("I am fired!")}
I see the first one "function" is not triggered on page load or refresh but where as second one fire() gets triggered
when page loaded, and later this function doesn't get triggered on click. I am confused, just need clarifications in this.
You need to pass fire
to onclick
as a function reference, not an invocation.
document.getElementById("Clk").onclick = fire;
When you pass fire()
to the onclick handler, it triggers immediately and the return from the function is what you are setting onclick too. By passing a reference to the function, it stops it from running until the event is triggered. It's essentially the same as the anonymous function handler above.
rlemon was kind enough to make you a nice demonstration fiddle <-- here
The second one fires immediately because you used parenthesis ()
. When assigning an event handler to an existing function, don't include the parenthesis.
What happens is the function executes straight away, and the return value is assigned as the event handler.
To illustrate, it is the same as doing:
var result = fire();
console.log( result ); // undefined
document.getElementById("Clk").onclick = result;
As you can see, undefined
is passed as the event handler.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With