Reputation: 43
I'm coding a game with different GameOver Text according to the score
Here's the code :
<div id="game-over">
<h3><font color="orange">Tu as courus <span id="score"></span> mètres.</font></h3>
<font color="orange"><h1 id="customegotext">oldHeader</h1></font>
<a href="javascript:void(0)" class="button restart">Ressayer ?</a>
</div>
</div>
<script>
var scoretext;
if (score < 45) {
scoretext = "Text1";
} else if (score > 100 ) {
scoretext = "Text2";
} else if (score > 500 ) {
scoretext = "Text3";
} else if (score > 750 ) {
scoretext = "Text4";
} else {
scoretext = "Text5";
}
document.getElementById("customegotext").innerHTML = scoretext;
</script>
The problem is that it always show "text5" whatever the score is.
Thank you for helping
Precision :
All of the code is in the index.HTML file
The value "score" is defined in a .JS file by this code
// define variables var player, score, stop, ticker;
I'm a beginner in coding
Upvotes: 0
Views: 44
Reputation: 1074248
The problem is that it always show "text5" whatever the score is.
There are two reasons for that:
score
is an HTMLElement, not a number. It's an automatic global variable created by the browser because you've given the element id="score"
. To access its value, you'd use score.value
, which is a string. You can convert that string to a number in various ways; this answer describes them.
You're running your script, just once, at the outset. Nothing will make it run automatically later when the value of the score
element changes. You need to do that on purpose. Search for "JavaScript event handling," "DOM event handling," or similar to see how to set up DOM event handlers.
Side note: I don't like to rely on automatic globals, not least because the global namespace in browsers is incredibly crowded and some id
values don't get an automatic global because they would conflict with an existing global. Instead, I suggest using document.getElementById("score")
to get the HTMLElement instance.
Upvotes: 3
Reputation: 576
Js is not aware of the html content which change, so you have to check out what is the value inside the span like this :
var score = document.getElementById("score").value;
You have to define score each time you want to reset the text.
Furthermore, your script is executed only one time when you open the page, so it will get the value of the default html which is undefined
because your span is empty. This is why you get "Text5"
.
If you want to do this dynamically, you have to create an event, for example when the user click on a button.
Upvotes: 1