I have a creative idea for a random ruffling game, where it picks a user's name and image randomly.
However, I'm facing an issue with ensuring that each image matches the correct user when selected randomly.
I want to make sure that every object in the json array with a name and image is properly matched during the random selection process.
How can I achieve this?
Here is my code:
script.js
const ENTRANTS = [{
name:"John",
image:"images/sun-rise.jpg"
},{
name:"Jack",
image:"images/tree-736885__480.jpg"
},{
name:"Jane",
image:"images/pexels-anjana-c-674010.jpg"
}];
const rollEl = document.querySelector(".roll");
const rollAgainEl = document.querySelector(".roll-again");
const namesEl = document.querySelector(".names");
const imageEl = document.querySelector(".image");
const winnerEl = document.querySelector(".winner");
const boxEl = document.querySelector(".text-box");
const winnerTextELEMENT = document.querySelector(".winnerText");
const values = Object.values(ENTRANTS)
winnerTextELEMENT.classList.add('hide')
function randomName() {
const rand = Math.floor(Math.random() * values.length);
const name = values[rand].name;
const image = values[rand].image;
namesEl.innerText = name;
imageEl.src = image
}
function rollClick() {
boxEl.classList.remove("hide")
rollEl.classList.add("hide");
rollAgainEl.classList.add("hide");
winnerEl.classList.add("hide");
namesEl.classList.remove("hide");
setDeceleratingTimeout(randomName, 10, 30);
setTimeout(() => {
namesEl.classList.add("hide");
winnerEl.classList.remove("hide");
rollAgainEl.classList.remove("hide");
const winner = namesEl.innerText;
winnerEl.innerText = winner;
winnerTextELEMENT.classList.remove('hide')
}, 4000);
}
function setDeceleratingTimeout(callback, factor, times) {
const internalCallback = ((t, counter) => {
return () => {
if (--t > 0) {
setTimeout(internalCallback, ++counter * factor);
callback();
}
};
})(times, 0);
setTimeout(internalCallback, factor);
}
index.html:
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>Ruffle</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
<link rel="stylesheet" href="./style.css">
</head>
<body>
<button class="roll" onclick="rollClick()">Start</button>
<span class="winnerText">WINNER</span>
<div class="text-box hide">
<img class="image" src=""/>
<div class="names hide">
</div>
<div class="winner hide"></div>
</div>
<button class="roll-again hide" onclick="rollClick()"> Start Again</button>
<script src="./script.js"></script>
</body>
</html>