<button class="btn">Generate Random Background Colors</button>
<ul class="sports-list">
<li>Football</li>
<li>Basketball</li>
<li>Tennis</li>
<li>Golf</li>
<li>Swimming</li>
</ul>
*,
*::before,
*::after {
box-sizing: border-box;
margin: 0;
padding: 0;
}
ul {
font-size: 1.3rem;
list-style-type: none;
width: 100px;
margin: auto;
}
li {
margin-top: 15px;
}
.btn {
font-size: 1.2rem;
color: #fff;
background-color: #8a2be2;
border: none;
border-radius: 15px;
padding: 10px;
cursor: pointer;
display: block;
margin: 10px auto;
}
.btn:hover {
background-color: #5a1d94;
}
const sportsList = document.querySelectorAll(".sports-list li");
const randomColorBtn = document.querySelector(".btn");
console.log(sportsList);
const lightColorsArr = [
"#FFDAB9",
"#FFE4B5",
"#FFFFE0",
"#FAFAD2",
"#F0FFF0",
"#E0FFFF",
"#AFEEEE",
"#00CED1",
"#00BFFF",
"#1E90FF",
"#ADD8E6",
"#7FFFD4",
"#7CFC00",
"#7FFF00",
"#32CD32",
"#ADFF2F",
"#FFFF00",
"#FFD700",
"#FFA500",
"#FF6347"
];
// fisher-yates shuffle algorithm
function shuffleArray(arr) {
let currentIndex = arr.length;
let randomIndex;
while (currentIndex !== 0) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
[arr[currentIndex], arr[randomIndex]] = [
arr[randomIndex],
arr[currentIndex]
];
}
return arr;
}
randomColorBtn.addEventListener("click", () => {
const shuffledColors = shuffleArray(lightColorsArr);
sportsList.forEach((list, index) => {
list.style.backgroundColor = shuffledColors[index];
});
});
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.