jQuery/javascript re-structuring issues -
issue:
i started using javascript/jquery little experience. had working code, after little bit of restructuring, died.
original code:
// floating navbar - side var names = ['#floatmenu','#header']; (var = 0; < names.length; i++){ floatobj(names[i]) } function floatobj(name) { var menuyloc = null; $(document).ready(function(){ menuyloc = parseint($(name).css('top').substring(0,$(name).css('top').indexof('px'))); $(window).scroll(function(){ var offset = menuyloc + $(document).scrolltop() + 'px'; $(name).animate({top:offset},{duration:0,queue:false}); }); }); };
re-structured code
$(document).ready(function(){ floatobj(); }); function floatobj() { var names = ['#floatmenu','#header']; var menuyloc = null; (var = 0; < names.length; i++){ menuyloc = parseint($(names[i]).css('top').substring(0,$(names[i]).css('top').indexof('px'))); $(window).scroll(function(){ var offset = menuyloc + $(document).scrolltop() + 'px'; $(names[i]).animate({top:offset},{duration:0,queue:false}); }); }; };
question:
i wondering if point out why restructuring code way doesn't work? wondering if there method of debugging javascript without additional add-ons? (it helpful if glaring mistakes pointed out.)
reason why.
the reason want re-structure code way because have other functions run @ load up. figured throw functions $(document).ready(function(){}) bit. if there's proper way of doing this, please enlighten me ><.
any appreciated! thanks.
the problem i
, when callback pass scroll
called, has value has @ end of loop (names.length
).
in first code, floatobj
function created scope storing value of names[i]
.
most solutions involve calling function in for
loop. if don't want call named external function, may :
for (var = 0; < names.length; i++){ (function(i){ // stores in scope of function menuyloc = parseint($(names[i]).css('top').substring(0,$(names[i]).css('top').indexof('px'))); $(window).scroll(function(){ var offset = menuyloc + $(document).scrolltop() + 'px'; $(names[i]).animate({top:offset},{duration:0,queue:false}); }); })(i); };
Comments
Post a Comment