Ok, I got it!
var divs = $('selector to get all divs'); // This could be $('img'); function shuffle(divs, iterations) { var size = divs.size(); for(var i = iterations; i > 0; i--) { // Pick two divs at random var div1 = divs[Math.floor(Math.random() * size)], div2 = divs[Math.floor(Math.random() * size)]; // Ensure they are different divs if(div1.is(div2)) { continue; } // Swap the two divs div1.clone().insertAfter(div2); div2.detach().insertAfter(div1); div1.detach(); } }; shuffle(divs, 1000);
Although this is likely to be better if you put divs .hide () and then divs .show () so you don't see the beating. However, maybe this is what you want? You might want to linger there and use the jQuery animation function to make it a fantasy. This particular solution requires the img position in the DOM to determine the location. A more complicated solution would be to swap the css position during the loop.
var savedLeft = div1.css("left"), savedTop = div1.css("top"); div1.css("left", div2.css("left")); div1.css("top", div2.css("top")); div2.css("left", savedLeft); div2.css("top", savedTop);
Actually I have NOT EXCLUDED this yet, but it looks right here: P
source share