6

I am trying to stop a floating (sliding) div when it reaches the bottom of a containing div but it isn't working. The variable bottom is the lowest point on the page of the containing div but for some reason doesn't act as it should. Anyone have a better method?

$(document).ready(function () {

    var top = $('#buttonsDiv').offset().top - parseFloat($('#buttonsDiv').css('margin-top').replace(/auto/, 0));
    var bottom = $('#mainBody').offset().top + $('#mainBody').height();

    $(window).scroll(function (event) {

        // what the y position of the scroll is
        var y = $(this).scrollTop();
        var z = y + $('#buttonsDiv').height();

        // whether that's below the form
        if (y >= top && z <= bottom) {
            // if so, add the fixed class
            $('#buttonsDiv').addClass('fixed');
        } else {
            // otherwise remove it
            $('#buttonsDiv').removeClass('fixed');
        }
    });
});
mskfisher
  • 3,291
  • 4
  • 35
  • 48
  • In your `.fixed` class, have you given `bottom: 0;` ? – techfoobar Dec 20 '11 at 16:53
  • i tried adding it and it still didnt work. the problem was finding a way for the scroll function to recognise the bottom of the floating element. I think i've solve that in the code above but getting it to stop at the bottom of the div containing it is baffling me. – user1108210 Dec 20 '11 at 18:33
  • 1
    Can you include your html and css and/or a working example? – James Montagne Dec 20 '11 at 22:04

2 Answers2

1

Try the below conditions:

 if (y >= top && z <= bottom) {
    // if so, add the fixed class
    $('#buttonsDiv').addClass('fixed');
 } else if(z > bottom) {
    // otherwise remove it
    $('#buttonsDiv').removeClass('fixed').addClass('absolute');
 } else {
    // otherwise remove it
    $('#buttonsDiv').removeClass('fixed');
 }

Once you scroll past the container DIV (#mainBody), the floating DIV (#buttonsDiv) should be positioned 'absolute' to the bottom of the container DIV.

Sandeep
  • 819
  • 10
  • 16
0

Simply defining a margin-bottom with floating div or padding-bottom with external div in this case should help. I have used a similar thing in the following website: www.emotionstorm.com to stop the shopping cart below the top banner. Please let me know if you need help for a similar code.