0

I've constructed this numbers counter script which counts numbers up to a target when they are in viewport. Unfortunately they are also counted down again for some reason.

$(window).scroll(function(){
  // This is then function used to detect if the element is scrolled into view
  function elementScrolled(elem)
  {
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();
    var elemTop = $(elem).offset().top;
    return ((elemTop <= docViewBottom) && (elemTop >= docViewTop));
  }

  // This is where we use the function to detect if ".numbers" is scrolled into view
  if(elementScrolled('.numbers')) {

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

  }
});

Here's the JSFiddle: http://jsfiddle.net/tw6g2oeu/325/

How could I stop the function from counting back?

EDIT

Ended up using the jQuery Waypoints plugin:

jQuery('.numbers').waypoint(function() {
  $('.arv').each(function () {
    $(this).prop('Counter',0).animate({
        Counter: $(this).text()
    }, {
        duration: 4000,
        easing: 'linear',
        step: function (now) {
            $(this).text(Math.ceil(now));
        }
    });
});
this.destroy()
},{offset:'75%'});

The this.destroy(); method prevents it from firing multiple times.

user3615851
  • 797
  • 1
  • 11
  • 30
  • You need to *debounce* your scroll event (there are other options). Basically, each time the window scrolls a tiny amount, your event fires - this may be 100s of times, each one taking 4 seconds to ease in-out. Add a `console.log("scroll")` inside the handler to see. – freedomn-m Feb 13 '17 at 10:13
  • scroll event is tricky you wont know how many times it is triggered. you can achieve what you try to achieve without events . check this http://stackoverflow.com/questions/487073/check-if-element-is-visible-after-scrolling – Khaleel Feb 13 '17 at 10:24

1 Answers1

1

since you added jQuery tag. you can use jQuery waypoint plugin. It ll do the job for you.

USAGE:

$('.entry').waypoint(function() {
   alert('You have scrolled to an entry.'); \\ increment your counter here
});
Khaleel
  • 1,129
  • 2
  • 13
  • 28