I used an alternate approach. I see that you are randomizing your list and then trying to remember whether the original elements were.
Instead of that, why don't you just shuffle elements based on whether they can be shuffled.
In the sense, take an array of the indexes for the switchable elements
denoted by the selector .sw
and then shuffle only those indexes.
Here's how the shuffle function would look like.
function shuffle(nodes, switchableSelector) {
var length = nodes.length;
//Create the array for the random pick.
var switchable = nodes.filter("." + switchableSelector);
var switchIndex = [];
$.each(switchable, function(index, item) {
switchIndex[index] = $(item).index();
});
//The array should be used for picking up random elements.
var switchLength = switchIndex.length;
var randomPick, randomSwap;
for (var index = length; index > 0; index--) {
//Get a random index that contains a switchable element.
randomPick = switchIndex[Math.floor(Math.random() * switchLength)];
//Get the next element that needs to be swapped.
randomSwap = nodes[index - 1];
//If the element is 'switchable' continue, else ignore
if($(randomSwap).hasClass(switchableSelector)) {
nodes[index - 1] = nodes[randomPick];
nodes[randomPick] = randomSwap;
}
}
return nodes;
}
On your button click, you can simply shuffle the nodes and then re-append them to the container.
$(".btn").click(function() {
var $nodes = $("#Items").find("li");
shuffle($nodes, "sw");
$("#Items").append($nodes);
});