Bah-Bee
Bah-Bee

Reputation: 2145

Fixing / Unfixing Div when scrolling

Basically i have 4 divs (a Banner, left content, right content, and a footer). The banner and left content divs are fixed while the right content and footer are not. What I'd like to have happen is when the top of the footer meets the bottom of the left content div have it unfix itself and scroll together with the right div.

I setup a preview of what i currently have in jsfiddle below.

http://jsfiddle.net/sgcer/270/

<div id="banner">BANNER</div>
<div id="content">
    <div id="left">LEFT</div>
    <div id="right">RIGHT</div>
</div>
<div id="footer">FOOTER</div>

#banner {
    float: left;
    width: 100%;
    height: 100px;
    background-color: #00ff00;
    position: fixed;
}
#content {
    height: auto;
}
#left {
    float: left;
    width: 30%;
    height: 600px;
    background-color: #ccc;
    position: fixed;
    margin-top: 100px;
}
#right {
    float: right;
    width: 70%;
    height: 750px;
    background-color: #333;
    margin-top: 100px;
}
#footer {
    clear: both;
    width: 100%;
    height: 100px;
    background-color: #ff0000;
}

Any help will be greatly appreciated!

Upvotes: 1

Views: 3780

Answers (3)

web2008
web2008

Reputation: 914

Try this:

$(window).scroll(function () {
        var ftop = $("#footer").position().top;
        var lbottom = $("#footer").position().top + $("#left").height();

        var scrollTop = $(window).scrollTop();
        var diff = ftop - scrollTop;

        if( diff <= lbottom)
        $("#left").css("position","static");
        else
        $("#left").css("position","fixed");
    });

Upvotes: 1

Albert Xing
Albert Xing

Reputation: 5788

I forked the Fiddle: http://jsfiddle.net/YK72r/2/

What I did is called an if on every scroll event, used a bit of metrics math to find the height needed, changed the css of the left sidebar using jQuery's css method, and then added an else statement to revert it when scrolling back up.

var scrollHeight;

$(window).ready(function() {
    scrollHeight = $('#footer').offset().top - $('#left').height() - $('#left').offset().top;
});

$(window).scroll(function() {
    if ($(document).scrollTop() >= scrollHeight) {
        $('#left').css({
            'position': 'relative',
            'margin-top': '350px'
        });
    } else {
        $('#left').css({
            'position': 'fixed',
            'margin-top': '100px'
        });
    }
});

Note that I changed the heights a bit, so mind the css pixel values.

Upvotes: 1

Alfred Xing
Alfred Xing

Reputation: 4632

Here are some general steps to do this:

  1. Use Javascript to get the pixel positions of the div and footer
  2. Using the onscroll listener, listen for when the footer should "unfix"
  3. When that happens, use className to add a class "fixed" to the footer

In your CSS, you should add:

.fixed { position: fixed; }

Using jQuery would make all of this easier, too.

Hope that helps!

Upvotes: 2

Related Questions