I want to randomly display a div class using JQuery. The code is something like:
One
Two
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! //-->
Something like that :
$('.item').hide().eq(Math.floor(Math.random()*4)).show()
Fiddle : http://jsfiddle.net/PPXmE/
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();
Demo
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);
var number = Math.floor(Math.random()*3)
var div = $(".item")[number];
div.show();