1

Hi I have an array of images, that get shuffled on the click of a shuffle button using the jquery shuffle function, what I also want to do is add a button to display only the first five images when its clicked.

So the question is how too pull the first 5 images from the array when a button is clicked??

The code is as follows:

HTML:

<div id="array" class="thirdcanvas"></div>
<button class="array">Shuffle</button>

JS:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<script>
jQuery(function ($) {

var arr = new Array("images/c1.png", "images/c2.png", "images/c3.png", "images/c4.png", "images/c5.png", "images/c6.png", "images/c7.png", "images/c8.png", "images/c9.png", "images/c10.png", "images/cj.png", "images/ck.png", "images/cq.png", "images/d1.png", "images/d2.png", "images/d3.png", "images/d4.png", "images/d5.png", "images/d6.png", "images/d7.png", "images/d8.png", "images/d9.png", "images/d10.png", "images/dj.png", "images/dk.png", "images/dq.png", "images/h1.png", "images/h2.png", "images/h3.png", "images/h4.png", "images/h5.png", "images/h6.png", "images/h7.png", "images/h8.png", "images/h9.png", "images/h10.png", "images/hj.png", "images/hk.png", "images/hq.png", "images/s1.png", "images/s2.png", "images/s3.png", "images/s4.png", "images/s5.png", "images/s6.png", "images/s7.png", "images/s8.png", "images/s9.png", "images/s10.png", "images/sj.png", "images/sk.png", "images/sq.png")

  $.each($.shuffle(arr), function (_, src) {
    $('<img />', {
        src: src
    }).appendTo('#array')
})
$('button.array').click(function () {
    $('#array').shuffle()
});
});

(function ($) {

$.fn.shuffle = function () {
    var _self = this,
        children = $.shuffle(this.children().get());
    $.each(children, function () {
        _self.append(this)
    })
    return this;
};

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

$( array ).slice( 0, 5 );

})(jQuery);
</script>

1 Answers1

0

I rewrote your code since it returned too many errors. I believe I achieved the functionality you were going for.

I used the shuffle() function to randomize the array. This is not a standard jQuery function, more info on that in this question.

I used the slice function to return the first 5 hits of the shuffled array. More info on slice.

I then used an each function for the shuffled split array to append the images to your target container.

$('button.array').on('click', function(){
    shuffle(arr);
    var firstFive = arr.slice(0, 5);   
    $('#array').empty();
    $.each(firstFive, function(i,v){
        console.log(v);
        $('#array').append('<img src="'+v+'">');
    });
});

Working example: http://jsfiddle.net/RD6Gu/3/

Community
  • 1
  • 1
timo
  • 2,119
  • 1
  • 24
  • 40