Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences between javascript function

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.

like image 976
user3556610 Avatar asked Jun 06 '14 19:06

user3556610


2 Answers

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

like image 84
Sterling Archer Avatar answered Sep 22 '22 19:09

Sterling Archer


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.

like image 43
MrCode Avatar answered Sep 19 '22 19:09

MrCode