user3615851
user3615851

Reputation: 990

Jquery number counter only once

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.

Upvotes: 0

Views: 730

Answers (1)

Khaleel
Khaleel

Reputation: 1371

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
});

Upvotes: 1

Related Questions