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

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -