code snippets
Here are some useful bits of code that I've used in my own sites. Feel free to copy, edit, whatever. No credit needed.
javascript: randomize an array
Paste this HTML where you want the randomized array in your page. Change HTML tag to div, li, span, etc., as needed.
<p id="display"></p>
Paste this JavaScript in a <script> tag after the HTML above or call it from a separate .js file.
// Array of HTML elements. Note that the inner quotes use double quotation marks ("") and the outer quotes use single quotation marks ('').
const myArray = [ '<img src="https://upload.wikimedia.org/wikipedia/commons/e/e8/Pixel_indigo_square.png">', '<img src="https://upload.wikimedia.org/wikipedia/commons/9/93/Pixel_pink_square.png">', '<img src="https://upload.wikimedia.org/wikipedia/commons/e/e0/Pixel_teal_square.png">', ];
// Apply Fisher-Yates Shuffle function
myFunction(array) { for (let i = array.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [array[i], array[j]] = [array[j], array[i]]; } return array; } const shuffleArray = myFunction(myArray);
// Remove commas from resulting array
const displayArray = shuffleArray.join(" ");
// Display final array
document.getElementById("display").innerHTML = displayArray;