0

I am a beginner in Jquery and I am trying to scroll an element in my page but I can't stop it properly when reaching the footer. It worked if I smoothly scroll down but in other case it's going down even if I try to avoid it with a personal function

Here is my JS code :

(function(jQuery) {
var element = jQuery('.sidebar'),
    element_footer = jQuery('.site-footer'),
    offset = element.offset().top,
    footer = element_footer.offset().top;

element.css('position', 'relative');

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

var move = true;
$(window).on('scroll', function(event) {
    var scrollTop = $(window).scrollTop();
    element_bottom = element.offset().top + element.outerHeight();

    if ( element_bottom > footer ) {
        if (move) {
            move = false;
            scrollTop_limit = scrollTop - (element_bottom - footer);
            element.stop(false, false).animate({
                top: scrollTop_limit
            }, 0);
        } else {
            if (scrollTop < scrollTop_limit) {
                move = true;
            }
        }            
    } else {
        move = true;
    }

    if ( move ) {
        element.stop(false, false).animate({
            top: scrollTop - offset + topMargin
        }, 0);
    }

});
})(jQuery);

I think that my function works in theory but in reality the offset().top is asynchronous and so even if my condition element_bottom > footer is false, on the page the element has reached the footer. (Just in the case if I scroll down fast)

I tried to use the scrollToFixed() function but without result.

Sorry if I am not clear enough in my explanations. Just let me know if you need more details.

Thank you in advance for your help.

  • If you are trying to make sticky sidebar you can use css method .sidebar { position: sticky; top: 40px; }. you don't have to do calculations for this. – Bikash Waiba Jun 10 '17 at 19:00
  • Otherwise you can use sticky sidebar plugin abouolia.github.io/sticky-sidebar – Bikash Waiba Jun 10 '17 at 19:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.