Rezler
Rezler

Reputation: 1074

Floating Scrolling Div with vertical constraints

What I am aiming for is along the lines of the example at http://net.tutsplus.com/tutorials/html-css-techniques/creating-a-floating-html-menu-using-jquery-and-css/

However I would like to constraint the floating div within another parent div.

E.g.

alt text http://img41.imageshack.us/img41/1686/72219115.png

I would like a menu div to be floating in the above light grey box, but it should not go outside out of it.

Any of the examples that I have seen for floating divs have all simply based their position off the top or bottom of the window. Has anyone tried to do this like the above?

Thanks.

Upvotes: 1

Views: 4690

Answers (2)

Rezler
Rezler

Reputation: 1074

After a bit more playing about, I got it working.

var menu = "#floatMenu";
    var menuYloc = null;

    $(document).ready(function(){

        var containerTop = $("#container").position().top;
        var containerLeft = $("#container").position().left;
        var containerHeight = $("#container").innerHeight();
        var menuHeight = $(menu).innerHeight();

        //Position the menu at the top-left of the container div
        $(menu).css('top', containerTop).css('left', containerLeft);

        menuYloc = parseInt($(menu).css("top").substring(0,$(menu).css("top").indexOf("px")))

        $(window).scroll(function () {

            //If the menu is within the container then move it down
            if($(document).scrollTop() > containerTop && $(document).scrollTop() < (containerTop + containerHeight - menuHeight))
            {
                offset = $(document).scrollTop()+"px";
                $(menu).animate({top:offset},{duration:400,queue:false});
            }

        });
    });

Upvotes: 0

Josh
Josh

Reputation: 6322

you need to define the maximum scroll height (maxscrollvalue) based on your wrapping div or a fixed value then amend the code as follows:

$(document).ready(function(){  
    menuYloc = parseInt($(name).css("top").substring(0,$(name).css("top").indexOf("px")))  
    $(window).scroll(function () {   
        var offset = menuYloc+$(document).scrollTop()+"px";  
        //new code here
        if(offset > maxscrollvalue){
            offset = maxscrollvalue;
        }
        $(name).animate({top:offset},{duration:500,queue:false});  
    });  
});   

all it does is check to see if the calculated offeset is bigger than your max and if it is bigger then just set it to the max value.

hope that helps. Josh

Upvotes: 3

Related Questions