javascript - anonymous function vs identical named function -


this question has answer here:

i'm having issues writing of first jquery code. i'm experimenting codecademy stuff, messing around , seeing how works. right i'm pretty confused issue anonymous functions: calling function anonymously works naming function , calling name not. code supposed to, on clicking icon, open menu left side of screen , shift rest of page right; reverse on clicking close icon. first code block works perfectly, second opens , closes menu after page loads , nothing. there i'm missing order of operations in js/jquery or what?

anonymous:

function main() {   $('.icon-menu').click(function() {     $('.menu').animate({left:'0px'}, 200);     $('body').animate({left:'285px'}, 200);   });   $('.icon-close').click(function() {     $('.menu').animate({left:'-285px'}, 200);     $('body').animate({left:'0px'}, 200);   }); } 

named:

function main() {   $('.icon-menu').click(open());   $('.icon-close').click(close()); }  function open() {   $('.menu').animate({left:'0px'}, 200);   $('body').animate({left:'285px'}, 200); } function close() {   $('.menu').animate({left:'-285px'}, 200);   $('body').animate({left:'0px'}, 200); } 

thanks can enlighten me.

you have

$('.icon-menu').click(open()); 

() calls function.

you calling open immediately , passing return value (undefined) click.

remove () , pass function instead.


Popular posts from this blog