Vegapunk
Vegapunk

Reputation: 99

jQuery - stop/cancel scroll event callback after a certain scroll position

I want the number to count up to its designated value and stay there, but because the function gets called every time the page is being scrolled below a certain height, then it goes back to 1.

The solution would be to make it call the function only once when the page has been scrolled to below the certain height.

Ive tried placing the .one() method several places but that didn't help

http://jsfiddle.net/d7vKd/1543/

$(document).on('scroll', function() {
  if ($(this).scrollTop() >= $("#mydiv").position().top) {
    window.randomize = function() {
      $('.radial-progress1').attr('data-progress', Math.floor(94));
    };
    $('.count').each(function() {
      $(this).prop('Counter', 0).animate({
        Counter: $(this).text()
      }, {
        duration: 6000,
        easing: 'swing',
        step: function(now) {
          $(this).text(Math.ceil(now));
        }
      });
    });
    setTimeout(window.randomize, 200);
  }
})

Upvotes: 1

Views: 733

Answers (1)

vsync
vsync

Reputation: 130165

You should unbind your scroll event once the callback has met its demands:

$(document).on('scroll.someName', function(){
  var isPassedPos = $(this).scrollTop() >= $("#mydiv").position().top;

  if( isPassedPos ){
    $(document).off('scroll.someName') // <-------------- remove the event listener

    window.randomize = function() {
      $('.radial-progress1').attr('data-progress', Math.floor(94));
    };

    $('.count').each(function() {
      $(this).prop('Counter', 0).animate({
        Counter: $(this).text()
      }, {
        duration: 6000,
        easing: 'swing',
        step: function(now) {
          $(this).text(Math.ceil(now));
        }
      });
    });

    setTimeout(window.randomize, 200);
  }
})

Upvotes: 1

Related Questions