Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

prototype: keep an element in view upon scrolling

Tags:

jquery

scroll

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.

like image 730
jskg Avatar asked Nov 05 '22 15:11

jskg


1 Answers

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');
        }
    }
}
like image 51
HurnsMobile Avatar answered Nov 12 '22 16:11

HurnsMobile