jqueryodometer

Run Odometer.js on dynamically created elements


I'm using Odometer to animate some values https://github.hubspot.com/odometer/

I see that it states:

Any libraries you're using to update their value, provided they don't update by erasing and rerendering the odometer element, will work just fine.

But this is what I need to do. Is there a way to get this to work with dynamically created elements? I've tried calling the entire library function again on my AJAX success but no dice...

I have elements on page load that do work correctly (the initial value of 0 is set via JS)

<strong id="odometer-away" class="odometer" data-value="'. $value .'"></strong>

And my js uses jQuery's .text() to set the elements value once scrolled into view. (pulled from the data attribute)

var odo = $('#odometer-away');
odo.text(parseFloat(odo.data('value')));

BUT When I create more of the elements via AJAX and load them to the page, the animations no longer work on those elements and I see that the elements do not contain any of the generated HTML from the odometer script that the elements have on pageload... So clearly something is not registering.

I can't find any information on this and I have looked pretty hard. Here is a fiddle where newly created elements do not animate.

Fiddle demo


Solution

  • Odometer probably looks for elements with the odometer class on document.ready, but you'd have to manually call it on new elements:

      var el = document.getElementById('new-odo');
      var new_odo = new Odometer({
        el: el
      });
      new_odo.update(999);
    

    Demo