javascriptjquerycssscrollfixed

Stop fixed position at footer


I'm looking for a solution to the popular issue of stopping a fixed object at the footer of the page.

I basically have a fixed "share" box in the bottom left corner of the screen and I don't want it to scroll over the footer, so I need it to stop about 10px above the footer.

I've looked at other questions here as well as others. The closest/most simple demo I could find is http://jsfiddle.net/bryanjamesross/VtPcm/ but I couldn't get it to work with my situation.

Here's the html for the share box:

    <div id="social-float">
        <div class="sf-twitter">
            ...
        </div>

        <div class="sf-facebook">
            ...
        </div>

        <div class="sf-plusone">
            ...
        </div>
    </div>

...and the CSS:

#social-float{
position: fixed;
bottom: 10px;
left: 10px;
width: 55px;
padding: 10px 5px;
text-align: center;
background-color: #fff;
border: 5px solid #ccd0d5;
-webkit-border-radius: 2px;
-moz-border-radius: 2px;
border-radius: 2px;
display: none;
}

The footer is #footer and it doesn't have a fixed height, if that makes any difference.

If someone could assist me in creating a simple jQuery solution for this, I'd much appreciate it!


Solution

  • Live demo

    first, check its offset every time you scroll the page

    $(document).scroll(function() {
        checkOffset();
    });
    

    and make its position absolute if it has been downed under 10px before the footer.

    function checkOffset() {
        if($('#social-float').offset().top + $('#social-float').height() 
                                               >= $('#footer').offset().top - 10)
            $('#social-float').css('position', 'absolute');
        if($(document).scrollTop() + window.innerHeight < $('#footer').offset().top)
            $('#social-float').css('position', 'fixed'); // restore when you scroll up
    }
    

    notice that #social-float's parent should be sibling of the footer

    <div class="social-float-parent">
        <div id="social-float">
            something...
        </div>
    </div>
    <div id="footer">
    </div>
    

    good luck :)