Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Showing random divs using Jquery

Tags:

jquery

I have a list if divs which contain images. I need to randomly show 4 of these each time the page loads. Here's the code I'm starting with.

<div class="Image"><img src="/image1.jpg"></div>
<div class="Image"><img src="/image2.jpg"></div>
<div class="Image"><img src="/image3.jpg"></div>
<div class="Image"><img src="/image4.jpg"></div>
<div class="Image"><img src="/image5.jpg"></div>
<div class="Image"><img src="/image6.jpg"></div>
<div class="Image"><img src="/image7.jpg"></div>

All of these will start as display:none, I'd like to take 4 of the divs at random and set them to display:block. I'm assuming I need to use "Math.random()" in there somewhere but not sure how JQuery does this. Any pointers would be appreciated.

like image 612
Mike Muller Avatar asked Nov 17 '10 14:11

Mike Muller


3 Answers

I find sorting them randomly then showing the first 4 to be the easiest, like this:

var divs = $("div.Image").get().sort(function(){ 
            return Math.round(Math.random())-0.5; //so we get the right +/- combo
           }).slice(0,4);
$(divs).show();

You can test it out here. If you want to also randomize the order (not just which are shown), you already have them sorted so just append them to the same parent in their new order by changing this:

$(divs).show();
//to this:
$(divs).appendTo(divs[0].parentNode).show();

You can test that version here.

like image 74
Nick Craver Avatar answered Nov 16 '22 20:11

Nick Craver


This does what you need: http://www.jsfiddle.net/Yn2pn/1/

$(document).ready(function() {
    $(".Image").hide();

    var elements = $(".Image");
    var elementCount = elements.size();
    var elementsToShow = 4;
    var alreadyChoosen = ",";
    var i = 0;
    while (i < elementsToShow) {
        var rand = Math.floor(Math.random() * elementCount);
        if (alreadyChoosen.indexOf("," + rand + ",") < 0) {
            alreadyChoosen += rand + ",";
            elements.eq(rand).show();
            ++i;
        }
    }
});
like image 31
Vincent Mimoun-Prat Avatar answered Nov 16 '22 21:11

Vincent Mimoun-Prat


jQuery(function($){
  var sortByN = function(a,b){ a=a.n; b=b.n; return a<b?-1:a>b?1:0 };
  $.each( $('div.Image').map(
    function(){ return { div:this, n:Math.random() }; }
  ).get().sort(sortByN), function(i){
    if (i<4) $(this.div).show();
  });
});

Note that this will always show the divs in the same order as the original. Is that acceptable?

like image 2
Phrogz Avatar answered Nov 16 '22 21:11

Phrogz