Created
April 28, 2017 15:36
-
-
Save hedleysmith/5258f49b353253470f074194040bfb20 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// $(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