1

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);
  }
})
vsync
  • 118,978
  • 58
  • 307
  • 400
Vegapunk
  • 99
  • 7

1 Answers1

1

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);
  }
})
vsync
  • 118,978
  • 58
  • 307
  • 400
  • Oh no, that solution created another issue, can your solution be isolated somehow? because i have another $(document).scroll(function(){ on my website that gets broken now :) – Vegapunk Aug 08 '17 at 12:34
  • $(document).scroll(function(){ if ($(this).scrollTop() > 400) { $("#topnav").removeClass("transp").addClass('wtbck'); } else { $("#topnav").removeClass("wtbck").addClass('transp'); } }); – Vegapunk Aug 08 '17 at 12:35
  • @Vegapunk - sure. update the solution to use [events namespace](https://api.jquery.com/event.namespace/) `someName` (choose your own), so the `off` method will only remove that specific event and not **all** the `scroll` event listeners. – vsync Aug 09 '17 at 07:31
  • i changed document to window, fixed it for me, hope it wont cause any issues on the different platforms :) – Vegapunk Aug 09 '17 at 09:31
  • @Vegapunk - it won't, but you should really use namespaces nonetheless. Any particular reason you have not chosen this answer as the correct one? – vsync Aug 09 '17 at 09:51