CoolBreezeUK CoolBreezeUK - 7 months ago 71
Javascript Question

Stop div from following scroll before it reaches the footer

I have been using the following script to make a div on my page float down as the page scrolls.

This is the script:

(function($) {
var element = $('.follow-scroll'),
originalY = element.offset().top;

// Space between element and top of screen (when scrolling)
var topMargin = 105;

// Should probably be set in CSS; but here just for emphasis
element.css('position', 'relative');

$(window).on('scroll', function(event) {
var scrollTop = $(window).scrollTop();

element.stop(false, false).animate({
top: scrollTop < originalY
? 0
: scrollTop - originalY + topMargin
}, 300);
});
})(jQuery);


This is the page: http://www.wedoblogging.com/faqs/ (U: wedoblogging P: cadb7b6c )

As you can see, the floating div (titled: Ask Us) keeps floating down into the footer, I would like this div to stop following the scroll before it reaches the green bar above the footer.

Thank you in advance for any help!

Answer

Similarly to this rule

top: scrollTop < originalY ? 0 : /*following code*/;

You add another rule that that contains the max position allowed:

var nextPosition = scrollTop - originalY + topMargin;
var maxPositionAllowed = 450;
top: scrollTop < originalY ? 0 : Math.min(nextPosition, maxPositionAllowed )

So whenever, the element tries to go bellow maxPostionAllowed, you will force it to have that distance from the top. I am not sure if 450 is the value that you want, but you can a few different to see how it looks.

So it would look something like this:

(function($) {
    var element = $('.follow-scroll'),
        originalY = element.offset().top;

    // Space between element and top of screen (when scrolling)
    var topMargin = 105;

    // Should probably be set in CSS; but here just for emphasis
    element.css('position', 'relative');

    $(window).on('scroll', function(event) {
        var scrollTop = $(window).scrollTop();
        var nextPosition = scrollTop - originalY + topMargin;
        var maxPositionAllowed = 450;

        element.stop(false, false).animate({
            top: scrollTop < originalY ? 0 : Math.min(nextPosition, maxPositionAllowed)
        }, 300);
    });
})(jQuery);
Comments