简体   繁体   中英

Run Function When a Scroll Event Does NOT Happen

I have an animation that I want to fire under 2 circumstances:

  1. When the page loads for the first time and the browser does not auto-scroll
  2. When the page is refreshed and the browser auto-scrolls the user back to their previous position, and that position ( scrollTop() ) is less than 300 .

I do not want the event to fire if:

  1. The user refreshes the page and the browser auto-scrolls to a position that is more than 300 .

The only way (that I know) to detect a browser auto-scroll is to fire this code:

$(window).load(function(){
    $(this).one('scroll', function(){
        var pagePosition = $('html').scrollTop();
    }
});

However if I run this code:

$(window).load(function(){
    // run on original page load (no scroll)
    myAnimation();

    // run on page refresh w/ auto-scroll
    $(window).one('scroll', function(){
        var pagePosition = $('html').scrollTop();

        if( pagePosition < 300 ) {
            myAnimation();
        }
    }
}

The animation will be fired twice on an original page load. Once when the page is loaded, and again when the user starts scrolling.

I need some way to detect if the browser auto-scrolls on load, and if it doesn't , then run the animation once.

Is this different than simply scrolling on load only if the scroll position is less than 300, eg:

$(window).load(function(){
    setTimeout(function() {
        var pagePosition = $('body').scrollTop();

        if( pagePosition < 300 ) {
            myAnimation();
        }
    }, 0);
}

Note that you should measure the scrollTop from the <body> element rather than <html> since some browsers always assign <html> a scroll position of 0 .

Working fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM