Shuffle Divs But Show Limited Number Of Them
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
Solution 1:
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();
returnfunction() {
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/
Solution 2:
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;
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="shuffle"><divclass="hue">one</div><divclass="hue">two</div><divclass="hue">three</div><divclass="hue">four</div></div>
Post a Comment for "Shuffle Divs But Show Limited Number Of Them"