0

I have this code which works fine, but when i scroll down, my div is reaching the footer and dont stop. How can I stop scrolling with page at certain point?

(function($) {
    var element = $('#div'),
        originalY = element.offset().top;

    var topMargin = 20;

    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);
Coddy
  • 15
  • 6

1 Answers1

0

You can use multiple multiple ternary operator to define which position do you want to stop at. This example have 2 point of stop, between stopTop 1 and stopTop 2. If scrollTop reach the stopTop1 then it will freeze on that position until scroll top pass the stopTop2 : top : scrollTop < originalY ? 0 : scrollTop > stopTop1 && scrollTop < stopTop2 ? stopTop1 : scrollTop - originalY + topMargin

Here the the code that you can try : myjsfiddle