2

I've looked around and have been able to find a piece of code that does the job but it doesn't work for all of my tags. I have a total of 8 Div tags that I want to randomize and this piece of code only allows me to randomize 7 of them. If I replace the 7 with an 8 it just shows everything in order. I don't work with Javascript very often and have hit a road block. Any help is greatly appreciated.

<script type="text/javascript">
$(document).ready(function() {
    $(".workPiece").hide();

    var elements = $(".workPiece");
    var elementCount = elements.size();
    var elementsToShow = 7;
    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;
        }
    }
});
</script>

3 Answers 3

4

This implementation of a Fisher-Yates shuffle seems to work quite well:

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/array/shuffle [rev. #1]

shuffle = function(v){
    for(var j, x, i = v.length; i; j = parseInt(Math.random() * i), x = v[--i], v[i] = v[j], v[j] = x);
    return v;
};

// Shuffle DIVs
$(document).ready(function() {
    console.log(shuffle($('div')));
});
Sign up to request clarification or add additional context in comments.

Comments

2

try this

var elements = $(".workPiece");
while (elements.length) {
   var rand = Math.floor(Math.random() * elements.length);
   elements.eq(rand).show();
   elements = elements.not(':eq(' + rand + ')');
}

But I don't know if this will work.

6 Comments

That's pretty clever! I had to modify it a bit to get it working: jsfiddle.net/noonat/sXRX4
It's ridiculous that you got a downvote for an elegant solution. I voted this up. Quite clever.
@Nathan Ostgard That works if you have more Divs then you actually want to show, i.e. you have 10 letters but you're only showing 7 of them. What I want to do is have 10 letters and then display all 10 randomly. Is there a way to do this?
@Andrew McNeil Ah, that's a bit more complicated. The randomization methods listed here all operate around hiding and showing elements -- random visibility, but not random ordering. What you want would need to remove the elements from the DOM, shuffle them, and add them all back in. Are your elements all in a single parent container?
@Nathan Ostgard Yes they are. Each one is assigned the class name "workPiece" and they are all housed within a div with class name "grid-8". Is that what you were asking?
|
1

To make this work with all elements, you need to actually move the elements themselves around to shuffle them, instead of just randomly hiding some of them.

Here is an example jQuery plugin to do that:

(function($) {
  $.fn.shuffle = function(selector, limit) {
    if (limit !== undefined) {
      limit -= 1;
    }
    return this.each(function() {
      var $this = $(this);
      var nodes = $this.children(selector).show().remove().get();
      while (nodes.length > 0) {
        var i = Math.floor(Math.random() * nodes.length);
        $this.append(nodes.splice(i, 1));
      }
      if (limit !== undefined) {
        $this.children(selector + ':gt(' + limit + ')').hide();
      }
    });
  };
})(jQuery);

You would call it like so:

$('.grid-8').shuffle('.workPiece');

You can limit the number of visible children like so:

$('.grid-8').shuffle('.workPiece', 4);

Here's a jsFiddle for it.

6 Comments

I looked at the jsFiddle and it works great but when I put it on the site it stops for some reason. I noticed that I gave you the wrong class name, it's "grid_8", but I made sure to change this and it still didn't work. This jsFiddle looks more like what the actual site does
I'm not sure why it wouldn't work for you -- even that jsFiddle you linked works. Is there any chance you can upload the site code itself somewhere?
Here is the page I'm working on.
@Andrew McNeil Hmm, when I open that page and paste the code into Firebug, it shuffles the elements as expected. Are you getting any JS errors? Side note: I updated the code, it wasn't re-showing elements when shuffled multiple times.
@Nathan Ostgard I put:$('.grid_8').shuffle('.workPiece', 4); in the head tag instead of right before the end body tag. It works perfectly now. Thanks for all your help!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.