Skip to content
Advertisement

stop counter on data attribute for multiple values

I have many divs that contain an data-attribute with a different value for each

I try to print this value by counting using javascript

JavaScript
JavaScript

The problem is that the counter doesn’t stop on the data-num value it counts to infinity

How can i stop the counter for each one in the value of data-num for each div?

Advertisement

Answer

What’s happening is that both elements are referencing the same variable counter, so the variable is actually incremented by two every call of the function. Therefore, you should have counters for each number. Likewise, you should have intervals for each number so you know when to stop incrementing.

Also, you need to replace number.dataset.num with parseInt(number.dataset.num) because that attribute is actually a string. As Parsa S said, you should also use classes instead of ids. After implementing all of the changes, here is the code:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement