Skip to content

Instantly share code, notes, and snippets.

@danielhaim1
Last active March 19, 2023 22:24
Show Gist options
  • Save danielhaim1/3e49dbfab04068e1fc4a to your computer and use it in GitHub Desktop.
Save danielhaim1/3e49dbfab04068e1fc4a to your computer and use it in GitHub Desktop.
Fisher-Yates shuffle algorithm to randomly select elements to show/hide.
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