jQuery sticky navbar -
i trying make sticky navbar sticks top when touches top, jquery code not working.
code(jquery):
function finddistance() { var disttotop = $(window).scrolltop(); var navoffset = $('#navbar').offset().top; var distance = (navoffset - disttotop); return distance; } $(document).ready(function() { var defaultnavdist = 166; var distance = finddistance(); var fixedset = false; $(window).scroll(function() { if(distance < 1 && fixedset == false) { fixedset = true; $('#navbar').css('position', 'fixed'); } }); });
link jsfiddle: http://jsfiddle.net/fj10ruqs/
when window scroll handler runs, distance not being recalculated. need put distance = finddistance();
inside scroll handler. you'll want add $('#navbar').css('top', '0');
when fixing top @ top.
$(window).scroll(function() { distance = finddistance(); if(distance < 1 && fixedset == false) { fixedset = true; $('#navbar').css('position', 'fixed'); $('#navbar').css('top', '0'); } });
Comments
Post a Comment