Patrick Patrick - 4 years ago 86
Javascript Question

How to make js function show random numbers rather than count

How can I change the following function so it will display random numbers instead of counting up to the final number?

$('.counter').each(function() {
var $this = $(this),
countTo = $this.attr('data-count');
$({
countNum: $this.text()
}).animate({
countNum: countTo
}, {
duration: 1000,
easing: 'linear',
step: function() {
$this.text(Math.floor(this.countNum));
},
complete: function() {
$this.text(this.countNum);
var element = document.getElementById('result');
element.style.opacity = "1";
element.style.filter = 'alpha(opacity=1)'; // IE fallback

var button = document.getElementById('return');
button.style.opacity = "1";
button.style.filter = 'alpha(opacity=1)'; // IE fallback

}
});
});


Thanks in advance.

Answer Source

This:

step: function() {
    $this.text(Math.floor(this.countNum));
},

Should be:

step: function() {
    var min = 5; // change min if you want to
    var max = 200; // change max if you want to
    $this.text(Math.floor(Math.random() * (max - min) + min)); // use Math.random to generate the random numbers
},
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download