getting this problem,that gameflash is not acting properly Uncaught TypeError: Cannot read properties of null (reading 'classList')
I am not really sure what am I doing wrong in manipulating DOM element for each form field. My form field has an stated name and ID of form and each input field has a name and id of the field as well. But I am still getting an error.
let gameSeq = [];
let userSeq = [];
let btns = ["red", "yellow", "green", "blue"];
let started = false;
let level = 0;
let h2 = document.querySelector("h2");
document.addEventListener("keypress", function() {
if (started == false) {
console.log("Game Started.....");
started = true;
levelUp();
}
});
function gameFlash(btn) {
btn.classList.add("gameflash");
setTimeout(() => {
btn.classList.remove("gameflash");
}, 500);
}
function userFlash(btn) {
btn.classList.add("userflash");
setTimeout(() => {
btn.classList.remove("userflash");
}, 500);
}
function levelUp() {
level++;
h2.innerText = `Level ${level}`;
let randomidx = Math.floor(Math.random() * 3);
let randomcol = btns[randomidx];
let randombtn = document.querySelector(`.${randomcol}`);
gameSeq.push(randomcol);
gameFlash(randombtn);
}
function check() {
let idx = level - 1;
if (userSeq[idx] === gameSeq[idx]) {
if (userSeq.length == gameSeq.length) {
levelUp();
}
} else {
h2.innerText = `Game Over! Press any key to Restart. `
}
}
function btnPress() {
let btn = this;
userFlash(btn);
usercolor = btn.getAttribute("id");
userSeq.push(btn);
check();
}
let allBtns = document.querySelectorAll(".btn");
for (btns of allBtns) {
btns.addEventListener("click", btnPress);
}
body {
text-align: center;
}
.btn {
height: 150px;
width: 150px;
border-radius: 20%;
border: 10px solid black;
margin: 1.5rem;
}
.btn-container {
display: flex;
justify-content: center;
}
.red {
background: #d95980;
}
.yellow {
background: #f99b45;
}
.blue {
background: #819ff9;
}
.green {
background: #63ffc0;
}
.gameflash {
background: #fff;
}
.userflash {
background: #c25744;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simon Game</title>
</head>
<body>
<h1>Simon Game</h1>
<h2>Press any key to start the game</h2>
<div class="btn-container">
<div class="box1">
<div class="btn red" type="button" id="red">1</div>
<div class="btn yellow" type="button" id="yellow">2</div>
</div>
<div class="box2">
<div class="btn green" type="button" id="green">3</div>
<div class="btn blue" type="button" id="blue">4</div>
</div>
</div>
</body>
</html>
I am trying to expecting that my gameflash error should resolve.