Treehouse: Grow your CSS skills. Land your dream job.

Last updated on:

Shuffle Children

Nice clean version of a ghetto one that I wrote.

$.fn.shuffleChildren = function() {
    $.each(this.get(), function(index, el) {
        var $el = $(el);
        var $find = $el.children();

        $find.sort(function() {
            return 0.5 - Math.random();
        });

        $el.empty();
        $find.appendTo($el);
    });
};

Usage

$(".parent-element").shuffleChildren();

View Demo

Comments

  1. this is cool I like it.

  2. Cool, nic1

  3. Steve
    Permalink to comment#

    … and if you want shuffle onload:

    <pre>$(window).load(function() {
    $(“.shuffle”).shuffleChildren();
    });
    </pre>

    Instead of demo page

    <pre>$(“#shuffle”).click(function() {
    $(“.shuffle”).shuffleChildren();
    });
    </pre>

    • ryan
      Permalink to comment#

      where would I place this? i am somewhat new to coding…I am using dreamweaver, and I have made a js plugin for the code, but where would I put the ‘usage’ aspect?

Leave a Comment

Posting Code

We highly encourage you to post problematic HTML/CSS/JavaScript over on CodePen and include the link in your post. It's much easier to see, understand, and help with when you do that.

Markdown is supported, so you can write inline code like `<div>this</div>` or multiline blocks of code in in triple backtick fences like this:

```
<script>
  function example() {
    element.innerHTML = "<div>code</div>";
  }
</script>
```