Search code examples
javascriptjqueryjquery-callback

JQuery:Passing callback method with or without braces giving different results


I have this code blocks from W3Schools sample of JQuery. Try it on W3Schools . I have only added one callback on the hide method call.

First Case

 <!DOCTYPE html> <html> <head> <script src="jquery.js"></script> <script> function sayHello(){ alert('hello sit'); }

$(document).ready(function(){   $("button").click(function(){
    $("p").hide(100,sayHello);   }); });

</script> </head> <body> <button>Hide</button> <p>This is a paragraph with little content.</p> <p>This is another small paragraph.</p> </body> </html>

The second case is

 <!DOCTYPE html> <html> <head> <script src="jquery.js"></script> <script> function sayHello(){ alert('hello sit'); }

$(document).ready(function(){   $("button").click(function(){
    $("p").hide(100,sayHello());   }); });

</script> </head> <body> <button>Hide</button> <p>This is a paragraph with little content.</p> <p>This is another small paragraph.</p> </body> </html>

The only difference in both is passing the callback function with or without braces.

In first case, on click of hide button I am getting hello alert twice. In second case I am getting hello alert only once. I am expecting the alert to come only once in both cases as it doesn't matter for a zero args function to be called with or without braces.

I would like to understand why it is calling callback function twice when function name is passed without braces.


Solution

  • In the second case, you're passing the result of evaluating sayHello(), whereas in the first case, you're passing the actual function sayHello.

    So because sayHello shows an alert, it will show the alert as soon as it's executed. In the first case, it's executed when hide is complete (as a callback), whereas in the second case it's executed when you set up the call to hide() (probably before the hide actually occurs).

    Not sure why it's executing twice, but (see below) the version without parenthesis (version 1) is probably the version you're looking for if you want it to execute once hide() is complete.

    UPDATE:

    The reason it's showing the alert twice is that you're calling hide() twice. You have two different <p> elements, and .hide() is being called for each of them in turn (and the callback is being executed for each in turn likewise). I would guess if you add a third <p> tag it will alert a third time.

    From the JQuery Docs:

    If multiple elements are animated, it is important to note that the callback is executed once per matched element, not once for the animation as a whole.

    You probably want to encompass your elements in a parent element (like a <div>) and hide that instead of each individual <p> element.