Reputation: 12171
I want to randomly display a div class using JQuery. The code is something like:
<div class="item">One</div>
<div class="item">Two</div>
<div class="item">Three</div>
<div class="item">Four</div>
So if the random method(random result is within 1 to 4) gives 3 as the result, it shows:
<div class="item">Three</div>
The rest are hidden. Of course, the code can be changed to make it worked. Thanks.
Upvotes: 11
Views: 21592
Reputation: 13
Use the setInterval function.
Working example: http://jsfiddle.net/a0c0ntjc/
setInterval(function(){
var E=document.getElementsByClassName("item");
var m=E.length;
var n=parseInt(Math.random()*m);for(var i=m-1;i>=0;i--){
var e=E[i];e.style.display='none';
}
E[n].style.display='';
},3000);
Upvotes: 0
Reputation: 15794
First we get a random int, from zero to the number of items (minus 1). Then we hide all other elements and show just the randomly chosen one.
var random = Math.floor(Math.random() * jQuery('.item').length);
jQuery('.item').hide().eq(random).show();
Upvotes: 27
Reputation: 8312
Working example: jsFiddle
window.onload=function() {
var E = document.getElementsByClassName("item");
var m = E.length;
var n = parseInt(Math.random()*m);
for (var i=m-1;i>=0;i--) {
var e = E[i];
e.style.display='none';
}
E[n].style.display='';
}
window.onload=function(){var E=document.getElementsByClassName("item");var m=E.length;var n=parseInt(Math.random()*m);for(var i=m-1;i>=0;i--){var e=E[i];e.style.display='none';}E[n].style.display='';}
<div class="item">One</div>
<div class="item">Two</div>
<div class="item">Three</div>
<div class="item">Four</div>
<div class="item">Five</div>
<div class="item">Six</div>
<!-- Add as many as you want! //-->
Upvotes: 2
Reputation: 33870
Something like that :
$('.item').hide().eq(Math.floor(Math.random()*4)).show()
Fiddle : http://jsfiddle.net/PPXmE/
Upvotes: 2
Reputation: 1174
var number = Math.floor(Math.random()*3)
var div = $(".item")[number];
div.show();
Upvotes: 3