Reputation: 353
I have a HTML slide menu. With the following:
<div class="slide">
<img typeof="foaf:Image" class="image-style-mylogo" src="http://site.com/1.png" alt="">
<img typeof="foaf:Image" class="image-style-mylogo" src="http://site.com/2.png" alt="">
<img typeof="foaf:Image" class="image-style-mylogo" src="http://site.com/3.png" alt="">
<img typeof="foaf:Image" class="image-style-mylogo" src="http://site.com/4.png" alt="">
<img typeof="foaf:Image" class="image-style-mylogo" src="http://site.com/5.png" alt="">
<img typeof="foaf:Image" class="image-style-mylogo" src="http://site.com/6.png" alt="">
</div>
And i want, get images with random sort every refresh. I used this code:
function reorder() {
var grp = $(".slide").children();
var cnt = grp.length;
var temp, x;
for (var i = 0; i < cnt; i++) {
temp = grp[i];
x = Math.floor(Math.random() * cnt);
grp[i] = grp[x];
grp[x] = temp;
}
$(grp).remove();
$(".slide").append($(grp));
}
function orderPosts() {
$(".slide").html(orig);
}
But don't work. What might I be doing wrong?
Upvotes: 0
Views: 500
Reputation: 72857
This should do it for you:
function reorder() {
var grp = $(".slide").children();
var cnt = grp.length;
var indexes = [];
// Build a array from 0 to cnt-1
for (var i = 0; i < cnt; i++) {
indexes.push(i);
}
// Shuffle this array. This random array of indexes will determine in what order we add the images.
indexes = shuffle(indexes);
// Add the images. (No need to remove them first, .append just moves them)
for (var i = 0; i < cnt; i++) {
$(".slide").append($(grp[indexes[i]]));
}
}
function shuffle(o){
for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
}
Working sample (I used spans instead of the images, to show the result better)
Upvotes: 0
Reputation: 173542
I'm not sure whether this is 100% kosher, but you could apply Fisher-Yates here, without dependency on jQuery.
fisherYates(document.getElementsByClassName('slide')[0]);
// Fisher-Yates, modified to shuffle DOM container's children instead of an array.
function fisherYates (node)
{
var children = node.children,
n = children.length;
if (!n) {
return false;
}
while (--n) {
var i = Math.floor( Math.random() * ( n + 1 ) ),
c1 = children[n];
node.insertBefore(c1, children[i]);
}
}
Upvotes: 1
Reputation: 108490
There is a much simpler way to do this. Since a jQuery collection is Array-like, you can call native Array prototypes on them. So using the native Array.sort
, your code you be rewritten like this:
var grp = $(".slide").children(); // the original collection, if you want to save it...
Array.prototype.sort.call(grp, function() {
return Math.round(Math.random())-0.5;
});
$('.slide').empty().append(grp);
Here is a demo: http://jsfiddle.net/JTGfC/
Upvotes: 2
Reputation: 451
Your reorder()
function is fine, I tested it in this fiddle : http://jsfiddle.net/kokoklems/YpjwE/
I did not used the second function orderPosts()
though...
Upvotes: 0