Gerico
Gerico

Reputation: 5169

jQuery get data attr from each and then perform count up animation

I'm trying to adjust a script I found on another stackoverflow question. Basically I want to be able to get the data attribute which is the count number and count from zero up to that number for each instance of that div.

Basically I'm trying to loop through each div element and make a variable of the data-attribute and then perform the count animation on that respective element.

My HTML:

  <div class="count_item" data-count="5000">0</div>

  <div class="count_item" data-count="444">0</div>

  <div class="count_item" data-count="6666">0</div>

My jQuery:

$(".count_item").each(function(i) {

  var count_val = $(this).data('count');

  $("body").append(count_val);
  console.log(count_val);

$({countNum: $(i).text()}).animate({countNum: count_val}, {
  duration: 8000,
  easing:'linear',
  step: function() {
    $(i).text(Math.floor(this.countNum));
  },
  complete: function() {
    $(i).text(this.countNum);
    alert('finished');
  }
});
});

I can't workout why if you look at the console it's getting two of the values and then it errors before the third. Help appreciated.

Working example: http://jsbin.com/yenunijemo/2/

Upvotes: 1

Views: 961

Answers (1)

Alvaro Montoro
Alvaro Montoro

Reputation: 29675

The issue is that i is not what you expect it to be (it is index of each .count_item in the selection array, but not the element in itself). An easy way to fix that would be to define a variable (e.g.: $this) that will contain the element that you are working with, and replace i with that variable.

If you try the following code, it will work fine:

$(".count_item").each(function(i) {

    var count_val = $(this).data('count');
    var $this = $(this);

    $("body").append(count_val);
    console.log(count_val);

    $({countNum: $this.text()}).animate({countNum: count_val}, {
        duration: 8000,
        easing:'linear',
        step: function() {
            $this.text(Math.floor(this.countNum));
        },
        complete: function() {
            $this.text(this.countNum);
            alert('finished');
        }
    });
});

You can see it working on this JSFiddle: http://jsfiddle.net/nqn09dd0/1/

Upvotes: 1

Related Questions