const buttonsContainer = document.getElementById('buttons');
const instruction = document.getElementById('instruction');
const message = document.getElementById('message');
// Function to generate a random number
const getRandomNumber = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
// Function to create the game
const createGame = () => {
const targetNumber = getRandomNumber(1, 10); // Change range as needed
instruction.textContent = `Click the number ${targetNumber}:`;
message.textContent = ''; // Clear the message
buttonsContainer.innerHTML = ''; // Clear the buttons
const totalButtons = 5; // Number of buttons to generate
const correctButtonIndex = getRandomNumber(0, totalButtons - 1); // Index to place the correct number
for (let i = 0; i < totalButtons; i++) {
const button = document.createElement('div');
// Assign the correct number to one button
if (i === correctButtonIndex) {
button.textContent = targetNumber;
} else {
let randomNumber;
do {
randomNumber = getRandomNumber(1, 10);
} while (randomNumber === targetNumber); // Ensure no duplicate of the target number
button.textContent = randomNumber;
}
button.className = 'button';
button.onclick = () => {
if (parseInt(button.textContent) === targetNumber) {
message.textContent = 'Correct! 🎉 Generating a new number...';
message.style.color = 'green';
setTimeout(createGame, 1000); // Start a new game after a short delay
} else {
message.textContent = 'Try again!';
message.style.color = 'red';
}
};
buttonsContainer.appendChild(button);
}
};
// Initialize the game
createGame();
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.