-1

Is there a simple jQuery way to generate numbers using a .class containing different numbers more and more increasing after a few seconds?

Example :

before :

<p class="number_vp">56</p>

<p class="number_vp">2</p>

after few seconds :

<p class="number_vp">58</p>

<p class="number_vp">10</p>
artSx
  • 1,560
  • 1
  • 12
  • 19

4 Answers4

3
var $p = $('.number_vp');

setInterval(function() {
    $p.html(function(_, num) {
        return +num + Math.floor(Math.random() * 6);
    })
}, 1000);

http://jsfiddle.net/eqseX/

Ram
  • 143,282
  • 16
  • 168
  • 197
  • +1 for the only answer (so far) with a numeric addition rather than a string concatenation, and for tidy use of a callback with `.html()`. – nnnnnn May 14 '13 at 10:34
  • Nice use of .html(function(index,elm){ return returnHTML; }); didn't know that existed :) – Willem Mulder May 14 '13 at 10:39
  • @WillemMulder - You can use that callback system with lots of jQuery functions. It's a nice feature. – nnnnnn May 14 '13 at 10:40
  • It certainly is! Although sometimes a more verbose version is easier to read, but that depends on the situation I guess :-) – Willem Mulder May 14 '13 at 10:41
1

Adding a random number between 1-100 for all 'number_vp' elements, every second:

setTimeout(function() {
    $(".number_vp").each(function(index,elm) {
        var value = $(elm).html()*1;
        var newValue = value + Math.round(Math.random()*100);
        $(elm).html(newValue);
    });
}, 1000);
Willem Mulder
  • 12,974
  • 3
  • 37
  • 62
  • 1
    Note that this adds a random number as a string concatentation, i.e., it adds more digits at the end... – nnnnnn May 14 '13 at 10:32
0

This code shows how to generate random numbers for your div items of class number_vp.

$('.number_vp').each(function(){
    var randomnumber=Math.floor(Math.random()*999);
    $(this).html(randomnumber);
});

Here is a live demo: http://jsfiddle.net/6JSXD/1/


This is a sample with a timer implemented, changing the values every 2 seconds.

setInterval(function(){
    changeNumbers();    
}, 2000);

function changeNumbers(){
    $('.number_vp').each(function(){
        var randomnumber=Math.floor(Math.random()*999);
        $(this).html(randomnumber);
    });
}

http://jsfiddle.net/6JSXD/2/

Dutchie432
  • 28,798
  • 20
  • 92
  • 109
0
setTimeout(genRandom,10000);


function genRandom(){$(".number_vp").each(function(index,elm) {
    $(this).html(Math.round(Math.random()*100000));
    setTimeout(genRandom,10000);
});}
Igor S.
  • 3,332
  • 1
  • 25
  • 33