Issue
I've been trying to create an end screen for my candy crush game utilizing a timer but for some reason when the timer hits 0 and the conditions are met, the screen doesn't come up. Any idea why this might be happening?
function timer() {
var seconds = 120;
var timer = setInterval(function() {
document.getElementById("safeTimerDisplay").innerHTML = seconds;
seconds--;
if (seconds < 0) {
clearInterval(timer);
}
}, 1000);
}
timer();
function endGame() {
if (seconds === 0 && score > 1800) {
console.log(endWindow1)
}
}
#EndWindow1 {
background: url("./endscreen.jpg") no-repeat center center fixed;
background-size: cover;
font-family: Arial, Helvetica, sans-serif;
color: white;
text-align: center;
}
<div id="EndWindow1" style="display:none;"></div>
<h1>Timer: <span id="safeTimerDisplay"></span></h1>
I tried using a conditional and stating that if the user's score was over 1800 and the clock hits 0, a specific image should come up that I specified using the file in the css folder. When the clock hits 0 though, nothing ends up happening and you can proceed with the game as normal.
Solution
There are a few issues here:
- Your element
EndWindow1
only has a background image but no content and a default height ofauto
. As the element is empty the height will be 0 and as such always invisible. - You never call the function
endGame()
. console.log()
does what the name suggests, it adds a console log entry for debugging purposes. It does not hide/show elements.- You never referenced your element
EndWindow1
but rather called a non-declared variable/constant.
window.addEventListener('DOMContentLoaded', function() {
const TIMER = document.getElementById('safeTimerDisplay');
const END_WINDOW = document.getElementById('EndWindow1');
let remaining_time = 10;
let score = 1801;
function timer() {
let timer = setInterval(function() {
TIMER.textContent = remaining_time;
remaining_time--;
switch (remaining_time) {
case 0:
endGame();
break;
case -1:
clearInterval(timer);
break;
default:
break;
}
}, 1000);
}
timer();
function endGame() {
END_WINDOW.classList.toggle('d-none', !(score > 1800));
}
})
#EndWindow1 {
background: url("https://via.placeholder.com/200.jpg") no-repeat center center fixed;
background-size: cover;
font-family: Arial, Helvetica, sans-serif;
color: white;
text-align: center;
height: 200px;
}
.d-none {
display: none;
}
<div id="EndWindow1" class="d-none"></div>
<h1>Timer: <span id="safeTimerDisplay"></span></h1>
Code Refining:
instead of using:
if (seconds === 0 && score > 1800) {
console.log(endWindow1)
}
and checking for 2 conditions you can add to your timer setInterval
the call for endGame
within your if condition. You already check there the time continuously.
You do not need an if
condition. YOu should hide/show elements by adding/removing CSS classes. As such you can use classList.toggle
to show/hide depending on a condition.
Answered By - tacoshy
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.