Search code examples
jqueryhtmlpositioning

jquery div positioning


Can someone help with this jsfiddle?

http://jsfiddle.net/4Ns44/

Intended purpose: when the page is scrolled down, link expands in the view port, This works good. But as we scroll up, I would like the expand window to stop where it started. ie, below the header div. Right now, the position:fixed is causing it to remain at top even after the header div becomes visible.

some help with position:fixed


Solution

  • If I understand what you're trying to do, I think you want to check for when scrollTop is less than the original position of #expand. In particular:

    var minY = $('#header').height();
    

    In the scroll handler:

    // this will reset to the original position
    if (top < minY) {
        $expand.css({position: "absolute", top: ''});
    }
    

    Resulting in this: http://jsfiddle.net/4Ns44/3/

    var minY = $('#header').height();
    var $expand = $("#expand");
    
    $(window).scroll(function () {
    
        var top = $(window).scrollTop();
    
        if($expand.css("position") === "fixed") {
    
            if(top > expandY) {
                $expand.css({position: "absolute", top: expandY});
            } else if (top < minY) {
                $expand.css({position: "absolute", top: ''});
            }
        }
        else {
            if (top < minY) {
                $expand.css({position: "absolute", top: ''});
            } else if(top < expandY) {
                $expand.css({position: "fixed", top: 0});
            }
        }
    });
    

    This is if I understand what you're trying to do...