javascript - Sticking Div to Top After Scrolling Past it -
right now, i'm able stick div
top after scrolls down 320px
wanted know if there way of achieving this. below have code:
jquery(function($) { function fixdiv() { if ($(window).scrolltop() > 320) { $('#navwrap').css({ 'position': 'fixed', 'top': '0', 'width': '100%' }); } else { $('#navwrap').css({ 'position': 'static', 'top': 'auto', 'width': '100%' }); } } $(window).scroll(fixdiv); fix5iv(); });
it works, divs
above not same height can't rely on 320px
. how work without using if ($(window).scrolltop() > 320)
can fade in @ top after user scrolls past div #navwrap
?
try using offset().top
of #navwrap
element. way element fixed it's starting position in document, regardless of is. example:
function fixdiv() { var $div = $("#navwrap"); if ($(window).scrolltop() > $div.data("top")) { $div.css({'position': 'fixed', 'top': '0', 'width': '100%'}); } else { $div.css({'position': 'static', 'top': 'auto', 'width': '100%'}); } } $("#navwrap").data("top", $("#navwrap").offset().top); // set original position on load $(window).scroll(fixdiv);
Comments
Post a Comment