I am learning jQuery, and am trying to understand how the callback works. I know what it does (calls some function after finishing with the first one), but it's the syntax that thrown me off a bit. I have this code:
showMenuElement( 0 ); // call to initiate the menu
function showMenuElement( x ) {
x += 1; // cycling through elements
if (x < 4) {
var el = "#menu-" + x;
$( el ).fadeIn( 1000, showMenuElement(x) ); // show one element, then show next in line
}
}
...and it doesn't work like I want it to, as it shows all the menu items at once! (here's the working fiddle: fiddle 1)
However, if I add the function() {...}
part, like this:
showMenuElement( 0 ); // call to initiate the menu
function showMenuElement( x ) {
x += 1; // cycling through elements
if (x < 4) {
var el = "#menu-" + x;
$( el ).fadeIn( 1000, function() { showMenuElement(x) } ); // show one element, then show next in line
}
}
then it works like a charm, showing one item after another (as per fiddle 2).
I am looking for the explanation for why it does behave this way?
I though, that since it's a callback, it will look for a name of a function to implement, so what does the writing function() {...}
explicitly changes?