Keep div inside view port or arbitrary div on scrolling

hurikhan77 picture hurikhan77 · Nov 29, 2009 · Viewed 7.3k times · Source

I'm trying to find a scriptaculous script (or create one) which keeps a vertical navigation bar "sticky" inside my viewport. While this may not be black magic (one could use the position:fixed css) there is a problem with this approach: If the navigation bar is longer than the viewport height the visitor won't be able to ever see the whole navigation. So I want that the navigation bar to not leave the viewport at its top but neither leave the parent container at its bottom. It should follow scroll events instantly without fancy/bouncing animations.

Is that possible? Google revealed nothing useful to me. You may know this kind of effect from slashdot's article comment navigator or google video's player box.

Update: Essentially that would be a rewrite of the jQuery plugin scrollFollow. It would be no problem if it lacked animations as I won't use them. But it should be able to stay within a defined parent container without clipping. The cookie handling is neither needed.

Answer

Chris picture Chris · Feb 2, 2011

I know this is really old but stumbled across this whilst trying to find my own solution

This link shows how to do it in a really lightweight fashion. Essentially all you need is the following code (along with jQuery loaded of course)

$(function() {
    var $sidebar   = $("#siderbar"),
        $window    = $(window),
        offset     = $sidebar.offset(),
        topPadding = 15;

    $window.scroll(function() {
        if ($window.scrollTop() > offset.top) {
            $sidebar.stop().animate({
                marginTop: $window.scrollTop() - offset.top + topPadding
            });
        } else {
            $sidebar.stop().animate({
                marginTop: 0
            });
        }
    });
})

If you don't want it to animate simply replace the animation sections like so:

$sidebar.stop().animate({ marginTop: VALUE });

with

$sidebar.css("marginTop", VALUE);