user460114
user460114

Reputation: 1848

Fast image shuffle

I'm trying to create a page with quickly shuffling images. By "shuffling", I mean randomly changing places (rapidly), as opposed to this jsfiddle example where the placement of the elements remains the same and a class is added to the randomly identified items to indicate the new selection. Following is the code to achieve this:

function shuffle(array) {
  var m = array.length, t, i;

  // While there remain elements to shuffle…
  while (m) {

    // Pick a remaining element…
    i = Math.floor(Math.random() * m--);

    // And swap it with the current element.
    t = array[m];
    array[m] = array[i];
    array[i] = t;
  }

  return array;
}

$(function() {
    $("button").click(function() {
        var $all = $("li").removeClass("selected");
        $(shuffle($all).slice(0, $("input").val())).addClass("selected");
    });
});

With my idea, if all the photos were assigned initially to divs, for example, how would I use similar shuffle() functionality to randomly change the divs the images are assigned to? Or any other way someone may have come up with?

Upvotes: 0

Views: 154

Answers (2)

stanley1943
stanley1943

Reputation: 877

Anyway, the way I did it was different from guest271314 which he did pretty good.

Just as another option. http://jsfiddle.net/fK8Xw/111/

$(function () {
    $("button").click(function () {
        var $all = $("li")
        $all.removeClass("selected");
        var data = shuffle($all).slice(0, $("input").val());
        var first = $(data).eq(0).prop('innerHTML');
        for (var i = 0; i < data.length; i++) {
            var next = $(data).eq(i + 1).html();
            if (i === data.length - 1) {
                $(data).eq(i).html(first);
            } else {
                $(data).eq(i).html(next);
            }
        }
        $(data).addClass("selected");
    });
});

Upvotes: 1

guest271314
guest271314

Reputation: 1

Try using .each() , .not() , .insertBefore() , .eq()

$(function () {
    $("button").click(function () {
        var $all = $("li").removeClass("selected");
        var selected = $(shuffle($all).slice(0, $("input").val()));
        selected.addClass("selected")
        .each(function () {
          $(this).insertBefore(
            $all.not(".selected")
            .eq(Math.random() * $all.not(".selected").length + 1)
          )
        });
    });
});

jsfiddle http://jsfiddle.net/fK8Xw/110/

Upvotes: 1

Related Questions