Last active
March 19, 2023 22:24
-
-
Save danielhaim1/3e49dbfab04068e1fc4a to your computer and use it in GitHub Desktop.
Fisher-Yates shuffle algorithm to randomly select elements to show/hide.
This file contains 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
window.addEventListener('DOMContentLoaded', function() { | |
var elements = document.querySelectorAll('.changing'); | |
var numOfElements = elements.length; | |
var numOfElementsToShow = 5; | |
if (numOfElements <= numOfElementsToShow) { | |
for (var i = 0; i < numOfElements; i++) { | |
elements[i].style.display = 'block'; | |
} | |
return; | |
} | |
// Shuffle the array of elements using the Fisher-Yates algorithm | |
for (var i = numOfElements - 1; i > 0; i--) { | |
var j = Math.floor(Math.random() * (i + 1)); | |
var temp = elements[i]; | |
elements[i] = elements[j]; | |
elements[j] = temp; | |
} | |
// Show the first numOfElementsToShow elements in the shuffled array | |
for (var i = 0; i < numOfElementsToShow; i++) { | |
elements[i].style.display = 'block'; | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment