Search code examples
javascripthtmlweb-frontend

CountUp javascript displays console error "[CountUp] target is null or undefined"


I'm new to CountUp.js and want to use it to optically count up a number.

In the following script (thats all I have till now) your can see the CountUp.js getting linked at the beginning. The CountUp.js is located in the folder "js", which is in the same directory as the file with the following code. After that, a javascript is started, which defines the options for the CountUp. Then a new CountUp-Instance is started, which has the ID "num0" and the final count-value of "150" at a final processing time of "5" seconds. The line that follows simply controls CountUp's behaviour by only starting if no error exists.

And here is the problem: The console says, that there is an error and the error is: [CountUp] target is null or undefined

I checked multiple google-entries, which describe bugs like

  • Wrong ID used in the javascript
  • Wrong src-Attribute of the script-tag
  • Wrong options-format

`

<html>
  <head>
    <script src="./js/countup.js" type="text/javascript"></script>
    <script>
      var options = {
        useEasing: true, 
        useGrouping: true, 
        separator: ',', 
        decimal: '.', 
      };
      var demo0 = new CountUp('num0', 0, 150, 0, 5, options);
      if(!demo0.error){demo0.start();}else{console.error(demo0.error);}
    </script>
  </head>
  <body>
    <span id="num0">0</span>
  </body>
</html>

`

I don't know what I'm doing wrong. It would be very nice if anyone could help me. Thank you!


Solution

  • It worked for me after wrapping it so that it runs only after the DOM is loaded. The script was running before the HTML element was loaded, so that is why the target was null. You could also move the script below the HTML element.

    Wrap it:

    document.addEventListener('DOMContentLoaded', function() {
    var options = {
        useEasing: true,
        useGrouping: true,
        separator: ',',
        decimal: '.',
    };
    var demo0 = new CountUp('num0', 0, 150, 0, 5, options);
    if (!demo0.error) {
        demo0.start();
    } else {
        console.error(demo0.error);
    }}, false);
    

    OR below the element

    <html>
      <head>
        <script src="./js/countup.js" type="text/javascript"></script>
      </head>
      <body>
        <span id="num0">0</span>
        <script>
          var options = {
            useEasing: true, 
            useGrouping: true, 
            separator: ',', 
            decimal: '.', 
          };
          var demo0 = new CountUp('num0', 0, 150, 0, 5, options);
          if(!demo0.error){demo0.start();}else{console.error(demo0.error);}
        </script>
      </body>
    </html>