Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop floating div at specified point using jQuery

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');
        }
    });
});
like image 793
user1108210 Avatar asked Dec 20 '11 16:12

user1108210


1 Answers

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.

like image 126
Sandeep Avatar answered Oct 20 '22 01:10

Sandeep