I'd like to keep a div element within the viewport when page is being scrolled. I'm currently using this snippet using jquery:
$(function() { var offset = $("#column-menu").offset(); var topPadding = 25; $(window).scroll(function() { if ($(window).scrollTop() > offset.top) { $("#column-menu").stop().animate({ marginTop: $(window).scrollTop() - offset.top + topPadding }); } else { $("#column-menu").stop().animate({ marginTop: 25 }); }; }); });
It works great but what happens is that the element disappear upon scrolling and then comes down from the top
-- what I would like instead -- The element stops as soon as its top border reaches the top of the viewport, no animation, no gliding no nuttin'.
It should be ie6,ie7 and ie8 compliant... Any suggestions (even with prototype) would be great. Thanks.
I am currently doing something very similar to this to keep a little summary info header at the top of long tables. Basically when you scroll past X (in this case 180px) then the div gets repositioned fixed to the top of the page. If you scroll back up past X then the div gets set back to its original position. No animations and no frills!
window.onscroll = function()
{
if( window.XMLHttpRequest ) {
if (document.documentElement.scrollTop > 180 || self.pageYOffset > 180) {
$('#StickyHeader').css('position','fixed');
$('#StickyHeader').css('top','0');
} else if (document.documentElement.scrollTop < 180 || self.pageYOffset < 180) {
$('#StickyHeader').css('position','absolute');
$('#StickyHeader').css('top','0px');
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With