Alex
Alex

Reputation: 12171

randomly display a div class using JQuery

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

Answers (5)

Donovan Botes
Donovan Botes

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

3dgoo
3dgoo

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();

Demo

Upvotes: 27

Ozzy
Ozzy

Reputation: 8312

Working example: jsFiddle

js

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='';
}

js.minified

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='';}

html

<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

Karl-Andr&#233; Gagnon
Karl-Andr&#233; Gagnon

Reputation: 33870

Something like that :

$('.item').hide().eq(Math.floor(Math.random()*4)).show()

Fiddle : http://jsfiddle.net/PPXmE/

Upvotes: 2

zarazan
zarazan

Reputation: 1174

var number = Math.floor(Math.random()*3)
var div = $(".item")[number];
div.show();

Upvotes: 3

Related Questions