Skip to content

Instantly share code, notes, and snippets.

@hedleysmith
Created April 28, 2017 15:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hedleysmith/5258f49b353253470f074194040bfb20 to your computer and use it in GitHub Desktop.
Save hedleysmith/5258f49b353253470f074194040bfb20 to your computer and use it in GitHub Desktop.
// $(document).ready() replacement.
function ready(fn) {
if (document.readyState != 'loading'){
fn();
} else {
document.addEventListener('DOMContentLoaded', fn);
}
}
// Randomise a set of items with the following structure:
// <div class="items"><div>Item 1</div><div>Item 2</div><div>Item 3 etc</div></div>
// Uses localStorage to save the order.
ready(function () {
var items = document.querySelector('.items');
var storedOrder = JSON.parse(localStorage.getItem("storedOrder"));
if (items) {
// If order has been saved in localStorage.
if (storedOrder) {
for (i = items.children.length; i > 0; i--) {
var index = i - 1;
items.appendChild(items.children[storedOrder[index]]);
};
} else {
// Order has not been saved, generate new random order and save.
var storedOrder = [];
for (i = items.children.length; i > 0; i--) {
var order = Math.floor(Math.random() * i);
storedOrder.push(order);
items.appendChild(items.children[order]);
};
localStorage.setItem("storedOrder", JSON.stringify(storedOrder));
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment