Created
June 17, 2024 15:38
-
-
Save marcomarkkez/53331159aab7521e66df3f5efbae3208 to your computer and use it in GitHub Desktop.
Random HTML elements with Vanilla JS
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
<script> | |
document.addEventListener("DOMContentLoaded", function(event){ | |
/* Fisher–Yates shuffle algorithm */ | |
var shuffle = function (array) { | |
var currentIndex = array.length; | |
var temporaryValue, randomIndex; | |
// While there remain elements to shuffle... | |
while (0 !== currentIndex) { | |
// Pick a remaining element... | |
randomIndex = Math.floor(Math.random() * currentIndex); | |
currentIndex -= 1; | |
// And swap it with the current element. | |
temporaryValue = array[currentIndex]; | |
array[currentIndex] = array[randomIndex]; | |
array[randomIndex] = temporaryValue; | |
} | |
return array; | |
}; | |
/* Implementation starts here */ | |
let elements = document.querySelectorAll( ".item" ); | |
let wrapper = document.querySelector( ".wrapper" ); | |
/* Copy */ | |
let newElements = Array.from( elements ); | |
/* Remove elements from wrapper */ | |
elements.forEach( (element, index) => { | |
element.parentNode.removeChild(element); | |
}); | |
/* Shuffle */ | |
let shuffleNewElements = shuffle(newElements); | |
/* Console log checking */ | |
console.group("shuffleNewElements:"); | |
shuffleNewElements.forEach( ( element, index ) => { | |
console.log("Element: "+index); | |
console.log(element); | |
}); | |
console.groupEnd(); | |
shuffleNewElements.forEach( (element,index) => { | |
let clon = element.cloneNode(true); | |
wrapper.appendChild(clon); | |
/* | |
Or | |
element.parentNode.appendChild(clon); | |
*/ | |
}); | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment