0

Basically, I want to have multiple divs on a page like below

<div id="count">10</div>
<div id="count">20</div>

And have a something run where all it does is find any div with the id "count" and just add whatever number is in there to itself every second and display the number.

So for the first div would display 10 to start, then the next second change to 20, then 30, then 40 and on and on forever and for the second div it would display 20 to start then show 40, then 60, then 80 and on and on forever as well.

Thanks in advance! :D

Disguy
  • 39
  • 6
  • 5
    ID's must be unique. Use classes instead. – Joel Almeida Jun 15 '15 at 16:36
  • But if I have a lot of them then I would need to make a new class for every one? That is fine by me but how would the javascript look like? Thanks for the help! – Disguy Jun 15 '15 at 16:37
  • No, you can use `count` as the class for all of them, only IDs must be unique. – APAD1 Jun 15 '15 at 16:38
  • To be clear, you're not adding the number to itself except for the very first time, right? I.e., you're incrementing each div by 10 and 20, respectively, with every iteration? You might start by trying to put something together on your own based on this post: http://stackoverflow.com/questions/4357145/javascript-get-html-or-text-from-div – Marc Jun 15 '15 at 16:40

2 Answers2

1

Nope, use class. Also add custom attribute to keep increment value.

HTML:

<div class="count" data-increment="10">0</div>
<div class="count" data-increment="20">0</div>

JS:

setInterval(function () {
    var counters = document.getElementsByClassName("count");

    for(var i = 0 ; i < counters.length ; i++) {
        counters[i].innerHTML = parseInt(counters[i].innerHTML) + parseInt(counters[i].dataset.increment);
    }
}, 1000);
Bancroy
  • 36
  • 4
-1
window.setInterval(function () {
    $('.count').each(function () {
        $(this).html(parseInt($(this).html()) + parseInt($(this).html()));
    });
}, 1000);
KidBilly
  • 3,408
  • 1
  • 26
  • 40
  • This code doubles the current value of each div on each interval, the OP wants to increment each value by the same number each time. – APAD1 Jun 15 '15 at 16:49