Reputation: 1899
Is there a simple jQuery way to create numbers randomly showing then a number 1 -6 is choosing after a few seconds? [Like dice]
Upvotes: 34
Views: 158908
Reputation: 1
Coding in Perl, I used the rand() function that generates the number at random and wanted only 1, 2, or 3 to be randomly selected. Due to Perl printing out the number one when doing "1 + " ... so I also did a if else statement that if the number generated zero, run the function again, and it works like a charm.
printing out the results will always give a random number of either 1, 2, or 3.
That is just another idea and sure people will say that is newbie stuff but at the same time, I am a newbie but it works. My issue was when printing out my stuff, it kept spitting out that 1 being used to start at 1 and not zero for indexing.
Upvotes: 0
Reputation: 7183
function rollDice(){
return (Math.floor(Math.random()*6)+1);
}
Upvotes: 3
Reputation: 27839
You don't need jQuery, just use javascript's Math.random
function.
edit: If you want to have a number from 1 to 6 show randomly every second, you can do something like this:
<span id="number"></span>
<script language="javascript">
function generate() {
$('#number').text(Math.floor(Math.random() * 6) + 1);
}
setInterval(generate, 1000);
</script>
Upvotes: 10
Reputation: 70701
This doesn't require jQuery. The JavaScript Math.random
function returns a random number between 0 and 1, so if you want a number between 1 and 6, you can do:
var number = 1 + Math.floor(Math.random() * 6);
Update: (as per comment) If you want to display a random number that changes every so often, you can use setInterval
to create a timer:
setInterval(function() {
var number = 1 + Math.floor(Math.random() * 6);
$('#my_div').text(number);
},
1000); // every 1 second
Upvotes: 99
Reputation: 20645
Javascript has a random()
available. Take a look at Math.random().
Upvotes: 0