Call Scroll only when user scrolls, not when animate()

℡╲_俬逩灬. 提交于 2019-11-27 14:53:25

You could make write your own code to set the animation value, and set a flag indicating that the change comes from an animation.

For example: (Untested)

var scrollAnimating = false
jQuery.fx.step.scrollTop = function(E) {
    scrollAnimating = true;
    E.elem.scrollTop = E.now;
    scrollAnimating = false;
};

$('#gototop').click(function() {
    $('body').animate({scrollTop:0},3000);
    $(window).scroll(function () {
        if (!scrollAnimating)
            $('body').stop();
    });
    return false;
})

You can do the same thing for scrollLeft.

Note that I'm assuming that setting scrollTop is a reentrant call, so that the scroll event is fired inside the line E.elem.scrollTop = E.now. If it's not reentrant (it might be only in some browsers), the event will be fired after scrollAnimating gets set back to false. To fix that, you could reset scrollAnimating inside the scroll event.

I was with the same problem, but I found a solution right on jQuery Documentation. There is a property in animate method that lets you set a callback function when animation is completed.

http://api.jquery.com/animate/#animate-properties-duration-easing-complete

Here is the code:

$('#gototop').click(function() {

    //This will help you to check 
    var animationIsFinished = false;

    $('body').animate({scrollTop:0},3000,"swing",function(){

        //this function is called when animation is completed
        animationIsFinished = true;

    });
    $(window).scroll(function () {
        //Check if animation is completed
        if ( !animationIsFinished ){
            $('body').stop();
        }
    });
    return false;
})

Figured it out! After looking around on the Internet I found something called Document.addEventListener for Mozilla and document.onmousewheel for IE and Opera that will catch scrolling events.

$('#gototop').click(function() {
    $('body').animate({scrollTop:0},3000);

    if(window.addEventListener) document.addEventListener('DOMMouseScroll', stopScroll, false);
    document.onmousewheel = stopScroll;

    function stopScroll() {$('body').stop()};

    return false;
})
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!