Kristen Grote
Kristen Grote

Reputation: 2777

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.

Upvotes: 0

Views: 199

Answers (1)

Stephen Thomas
Stephen Thomas

Reputation: 14053

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

$(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

Upvotes: 1

Related Questions