How to call a function after scroll has ended?

后端 未结 4 890
渐次进展
渐次进展 2021-01-14 17:30

I want to call a function right after a scroll ends. I have tried a load of different things, none of which have quite worked, and then I came upon this solution in

相关标签:
4条回答
  • 2021-01-14 18:02

    The jQuery throttle/debounce plugin is perfect for this. Use at_begin = false to execute the callback at the end.

    var scrollEnded = $.debounce(500, false, function ()
    {
        console.log('scroll ended');
    });
    
    $('#scrollableDiv').scroll(scrollEnded);
    

    Demo

    0 讨论(0)
  • 2021-01-14 18:02

    As an addition to all this answers I would only suggest setting 200ms timeout instead of 500. 200ms is the average human eye reaction between finger move and the eyes expecting to see the effect. 200ms timeout should be short enough to not be noticed by user and long enough for javascript to fire and finish the event. I've tried 200ms before and it seems to work just fine, even on slower PC's.

    0 讨论(0)
  • 2021-01-14 18:12

    have you tried putting scrollEnded() on top of bodyScroll()?

    function scrollEnded(){
        console.log('scrollEnded. Now do something astounding.');
    };
    function bodyScroll() {
        console.log('scrolling.');
    
        if (scrollTimer != -1)
            clearTimeout(scrollTimer);
    
        scrollTimer = window.setTimeout('scrollEnded()', 500);
    
    };
    
    0 讨论(0)
  • 2021-01-14 18:16

    Sorry, I completely ignored the fact that the function was within the closure, and therefore not available to the page in my earlier response. You could make it work via something like:

    window.scrollEnded = function () { console.log('scrollEnded. No do something astounding'); }
    

    followed by a

    window.setTimeout(window.scrollEnded, 500);
    

    That should remove the eval of the string, as well as put it in a global scope to where it is available. There are other oddities about that in terms of namespace pollution, but for the time being I'm trying to be somewhat simple and help you get it work.

    0 讨论(0)
提交回复
热议问题