Question: I have the following code. The code changes the buttons color when clicked. How would I remove inner.HTML to seperate the HTML, JSS and CSS
I have the following code. The code changes the buttons color when clicked. How would I remove inner.HTML to seperate the HTML, JSS and CSS files. All functionality needs to be in the JS file and styling in seperate CSS file.
HTML Code ( Commented )
/* CSS */
body {
width: 100%;
height: 700px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.btns {
width: 40px;
height: 40px;
padding: 10px;
margin: 10px;
font-weight: bolder;
}
.newGame {
height: 50px;
width: 150px;
margin-top: 50px;
font-weight: bolder;
}
// Initializing the necessary variables
let count = 25;
let list = [];
// Initialization function definition
function initializeGame() {
// Setting previous clicked button counts to 0
let prev = 0;
// Emptying out the button container
document.querySelector(".buttonGrid").innerHTML = "";
// Resetting the background color to white
document.body.style.backgroundColor = "white";
// Generating an array with number 1-25
for(let i = 0; i < 25; i++) {
list.push(i+1);
}
// Shuffling the array
list = list.sort(() => Math.random() - 0.5);
generateButtons();
// Function to generate all the 25 buttons
function generateButtons() {
// Run the loop 25 times
for(let j=0; j < 25; j++) {
// Create a new button element
let btn = document.createElement("button");
// Adding the button number
btn.innerHTML = list.pop();
// Adding the button class
btn.classList.add("btns");
// Adding the newly created button into the container div
document.querySelector(".buttonGrid").appendChild(btn);
// Making each of the row contain 5 buttons
if((j+1) % 5 == 0) {
// Creating a new row in the container div
let newline = document.createElement("br");
document.querySelector(".buttonGrid").appendChild(newline);
}
}
}
// Selecting all the 25 buttons
document.querySelectorAll(".btns").forEach(item => {
// Adding click event listener to each button
item.addEventListener("click", event => {
// If the clicked button is in the right order
if(event.target.innerHTML == prev + 1) {
// Change the background color to a random color
document.body.style.backgroundColor = 'rgb(' + Math.random() * 255 + ',' + Math.random() * 255 + ',' + Math.random() * 255 + ')';
// Incrementing prev
prev += 1;
// If all the 25 buttons are clicked
if(prev == 25) {
// Display the won message
setTimeout(function(){ alert("YOU WON!!!"); }, 150);
}
}
})
});
}
REQUIREMENTS
All event listeners should be named functions No global variables All styling in CSS file All events and functionality in JavaScript file Multiple functions JSDoc Comments on all functions No use of console.log, alert, prompt, or confirm
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
