Search code examples
jqueryhtmlpositioning

Jquery positioning dynamic div scrolltop


I have a two column webpage. the first(id="#list") is a list of divs and it can get longer with content. The second(id="#expand") is an expanded view, when a div is clicked on the left column. Imagine twitter like layout, with a new column on the right side.

Users keep scrolling down to see left div. When they click on any one of that divs,

  1. how can I position the right ("#expand") div in the viewing area. ?
  2. If they scroll down, "#expand" should behave normal, as in it should be where it is.
  3. If they scroll up, "#expand" should move up, until hitting the top.

Can someone help? NOTE: #expand is DYNAMIC, brought in via AJAX

Thanks


Solution

  • You want to switch between position: fixed, top: 0 and position: absolute, top: <the current scroll position> as the user scrolls past the "top" of the #expand element. The code below uses a (not quite) global variable to track where this switch should occur. You could use $("#expand").data(...) or something else if you prefer, but you get the idea.

    (function () {
    var expandY = 0;
    $("a[name=somelink]").click(function (e) {
        e.preventDefault(); // Keep from following link.
        expandY = $(window).scrollTop();
        $("#expand").css({position: "fixed", top: 0});
    });
    
    $(window).scroll(function () {
        var $expand = $("#expand");
        if($expand.css("position") === "fixed") {
            if($(window).scrollTop() > expandY) {
                $expand.css({position: "absolute", top: expandY});
            }
        }
        else {
            if($(window).scrollTop() < expandY) {
                $expand.css({position: "fixed", top: 0});
            }
        }
    });
    
    })();
    

    Here's the fiddle:

    http://jsfiddle.net/rkp5x/3