inorganik/countUp.js

How to use the counted up value in e.g. a function

derbalint opened this issue · 4 comments

[ ] Bug
[x ] Feature request

CountUp.js version: 2.0.4

Description

Everything works great, thanks for this!
But how can I display/store the numbers/value that are counted up somewhere else than in an element with an id. For example I would like to have a

let x = counter;

so that i can work with x in another function.
I tried to get the values out of an input with oninput and onchange but they don't work as the values are changed via countUp.js and not by a user.

Any help on that?

I'm not sure I understand completely, sounds like you want the frame-by-frame values as it's counting, is that right?

Hey, thanks for your answer! Yes exactly, and save them in a let or var for further use.

I found a solution using MutationObserver and adding the className="observable" to the div where the textContent is being counted up by countup.js

This works, but if you have a better/faster solution I would be very happy to see/learn it (:

var observer = new MutationObserver(function(mutations){ mutations.forEach(function(mutation){ let saveCount = mutation.addedNodes[0].textContent; console.log(saveCount); }); });

    function addObserverIfDesiredNodeAvailable() {
        var countElement = document.querySelector(".observable");
        if(!countElement) {
            window.setTimeout(addObserverIfDesiredNodeAvailable,1);
            return;
        }
        var config = {characterData:true, subtree: true, childList: true};
        observer.observe(countElement,config);
    }
    addObserverIfDesiredNodeAvailable();

You can access the frameVal property:

    const demo = new CountUp('myTargetElement', endVal, options);
    setInterval(() => {
      console.log('frameVal', demo.frameVal)
    }, 300);

which would output something like

frameVal 305
frameVal 1245
frameVal 2287

If you want to be notified every time the value changes, pass a custom formatting function, because you can use it like a frame-by-frame callback:

const format = (num) => {
  // do something with num
  return num + ''; // return string, this gets printed in the DOM
}
const options = { formattingFn: format }
demo = new CountUp('myTargetElement', endVal, options);

Hope that helps

Thank you so much! Thats absolutely perfect and saves me the whole MutationObserver.
CountUp.js is a really great class, thank you for that!