Reputation: 499
I'm using this code to shuffle elements of div every n seconds .. is there a way to display only 2 elements (for example ) with each shuffle ?
var parent = $("#shuffle");
var divs = parent.children().slice();
setInterval(function() {
var clone = divs.slice(); // <-- clone, since splice modifies array
while (clone.length) {
parent.append(clone.splice(Math.floor(Math.random() * clone.length), 1)[0]);
}
}, 2000); // <-- shuffle each 2 seconds
http://jsfiddle.net/yxBhH/1/ I'm Interested in Javascript solution
Upvotes: 0
Views: 402
Reputation: 45252
Here's an easy solution.
On each interval, clear out all of the elements, and then add n
elements randomly picked from the list.
var populateParent = (function() {
var parent = $("#shuffle");
var divs = parent.children().slice();
return function() {
parent.empty();
var clone = divs.slice();
for (var i = 0; i < 2 && i < divs.length; ++i) {
parent.append(clone.splice(Math.floor(Math.random() * clone.length), 1)[0]);
};
}
})();
populateParent();
setInterval(populateParent, 2000);
http://jsfiddle.net/rv7zpd07/5/
Upvotes: 1
Reputation: 16777
You can limit the number of div
s displayed using another :nth-child
CSS rule. If you want to display only two, for example, you would use:
.hue:nth-child(n+3) {
display: none;
}
var parent = $("#shuffle");
var divs = parent.children().slice();
setInterval(function() {
var clone = divs.slice();
while (clone.length) {
parent.append(clone.splice(Math.floor(Math.random() * clone.length), 1)[0]);
}
}, 2000);
.hue {
background: #ddd;
display: block;
}
.hue:nth-child(2n) {
background: yellow;
display: block;
}
.hue:nth-child(n+3) {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="shuffle">
<div class="hue">one</div>
<div class="hue">two</div>
<div class="hue">three</div>
<div class="hue">four</div>
</div>
Upvotes: 0