Skip to content

Commit

Permalink
Update randomize-element.js
Browse files Browse the repository at this point in the history
  • Loading branch information
jonaharagon committed Mar 15, 2024
1 parent 7f348fc commit 150bcb7
Showing 1 changed file with 9 additions and 8 deletions.
17 changes: 9 additions & 8 deletions theme/assets/javascripts/randomize-element.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ let globalData = document.querySelector("#global-data");
if (globalData.dataset.randomizeElement) {
// Get elements to be randomized from meta tag in HTML
let randomizeElement = globalData.dataset.randomizeElement;
console.log("Randomizing child elements of " + randomizeElement)
console.log("Randomizing child elements of " + randomizeElement);

// Get all elements to be randomized
let randomizeChildren = document.querySelectorAll(randomizeElement);
Expand All @@ -49,14 +49,15 @@ if (globalData.dataset.randomizeElement) {
let randomChildren = Array.from(children)
.map(value => ({ value, sort: Math.random() }))
.sort((a, b) => a.sort - b.sort)
.map(({ value }) => value)
.map(({ value }) => value);

// Clear the contents of the element
children.forEach(e => e.remove());

// Iterate over each element of randomChildren
for (const childElement of randomChildren) {
element.appendChild(childElement);
// Replace each element with randomly selected element
for (let i = 0; i < children.length; i++) {
let child = randomChildren[i].cloneNode(true);
child.classList.add("randomized");
let parent = children[i].parentNode;
parent.insertBefore(child, children[i]);
children[i].remove();
}

}
Expand Down

0 comments on commit 150bcb7

Please sign in to comment.