I’m doing a gaming project for javascript learning and i’ve hit a road block. I think my code looks the same to my mentors but no effect. What’s wrong?
``
``
I’m doing a gaming project for javascript learning and i’ve hit a road block. I think my code looks the same to my mentors but no effect. What’s wrong?
``
``
Please post actual code (HTML, CSS, JS) instead of a screenshot. Also, explain in detail what you are expecting the code to do vs. what is happening instead.
The square Id needs to be represented so i can connect it to the grid on my webpage. Im creating a whac-a-mole game. Very basic design. So every time the square that the ‘mole’ is on is clicked an event will happen.
squares.forEach(square => { square.addEventListener('mousedown' () => { if (square.id == hitPosition) { result++ score.textContent = result hitPosition = null } }) })
it’s not understanding my square.id for some reason
Please post full code (HTML, CSS, JS).
Thank you.
const squares = document.querySelectorAll(".square");
const mole = document.querySelector(".mole");
const timeLeft = document.querySelector("#time-left");
const score = document.querySelector("#score");
let result = 0;
let hitPosition;
function randomSquare() {
squares.forEach((square) => {
square.classList.remove("mole");
});
let randomSquare = squares[Math.floor(Math.random() * 9)];
randomSquare.classList.add("mole");
hitPosition = randomSquare.id;
}
squares.forEach(square => {
square.addEventListener('mousedown' () => {
if (square.id == hitPosition) {
result++
score.textContent = result
hitPosition = null
}
})
})
function moveMole() {
let timerId = null;
timerId = setInterval(randomSquare, 500);
}
moveMole();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Whac-a-mole</title>
<link rel="stylesheet" href="index.css" />
</head>
<body>
<h2>Your score:</h2>
<h2 id="score">0</h2>
<h2>Time left:</h2>
<h2 id="time-left">60</h2>
<div class="grid">
<div class="square" id="1"></div>
<div class="square" id="2"></div>
<div class="square" id="3"></div>
<div class="square" id="4"></div>
<div class="square" id="5"></div>
<div class="square" id="6"></div>
<div class="square" id="7"></div>
<div class="square" id="8"></div>
<div class="square" id="9"></div>
</div>
<script src="index.js"></script>
</body>
</html>
.grid {
display: flex;
width: 606px;
height: 606px;
flex-wrap: wrap;
}
.square {
height: 200px;
width: 200px;
border: solid black 1px;
}
.mole {
background-color: blue;
}
You have a syntax error here that you should be seeing as an error message in your browser console.
Ok thanks . I’ll check on it and make the proper correction.
Fixed it. I literally just needed a comma lol