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.
In the second case, you’re passing the result of evaluating
sayHello(), whereas in the first case, you’re passing the actual functionsayHello.So because
sayHelloshows an alert, it will show the alert as soon as it’s executed. In the first case, it’s executed whenhideis complete (as a callback), whereas in the second case it’s executed when you set up the call tohide()(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 oncehide()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:
You probably want to encompass your elements in a parent element (like a
<div>) and hide that instead of each individual<p>element.