1

I'm working on a game that when you get 10 strikes, there should be a alert telling you Game Over. The alert is not working. The StrikeNumber ID is the ID of the DIV that once it is 10, the alert should happen. This is pure Java Script.

function GameOver(){
if (document.getElementById('StrikeNumber').text === "10"){
    alert("gameOVER");
   }
}


HTML DIVS

<div id="StrikeNumber">
0
</div>
<div id="ScoreNumber">
0
</div>
Graham
  • 11
  • 2

6 Answers6

2

If you are using JQuery then you can use the .change() method and write logic inside that method.

$("#StrikeNumber").change(function(){ alert('strike changed'); });

Shabareesh
  • 25
  • 2
  • I'm using pure java script. – Graham Oct 27 '17 at 03:54
  • 1
    @Graham here's a pure JavaScript translation of the above: `document.getElementById('#StrikeNumber').onchange = function() { alert('strike changed') };` – Epoch Oct 27 '17 at 04:08
1

The div element dose not have a text property. You have to use the textContent property.

if (document.getElementById('StrikeNumber').textContent === "10"){
    alert("gameOVER");
   }

get text from doc tag

andre mcgruder
  • 1,120
  • 1
  • 9
  • 12
1

There is no text , use innerHTML or textContent . Your html look like having whitespace so using trim() is a better solution . You need to learn == & === difference at here

function GameOver(){
if (document.getElementById('StrikeNumber').innerHTML.trim() == "10"){
     alert("gameOVER");
   }
}
Jack jdeoel
  • 4,554
  • 5
  • 26
  • 52
1

Try following code might help you

(function() {

    var x = document.getElementById("StrikeNumber").innerHTML;

    if (x == 10) {
      alert("Game Over !!!");
    }

  }

)();
<div id="StrikeNumber">
  10
</div>
<div id="ScoreNumber">
  0
</div>
Nisal Edu
  • 7,237
  • 4
  • 28
  • 34
0

You should use innerHTML to get the content of a div.

function GameOver(){
    if (document.getElementById('StrikeNumber').innerHTML === "10"){
    alert("gameOVER");
   }
}

You also need to make sure that the GameOver() method is called after every div content update.

H H
  • 366
  • 1
  • 6
  • I have tried this and it does not work. Thanks for response though. – Graham Oct 27 '17 at 03:33
  • How would I go about making sure the method is called after every time the div is updated? – Graham Oct 27 '17 at 03:52
  • You call it right after the action that you use to update the Dev. you also need to make sure that the div contains "10" without any whitespaces. – H H Oct 27 '17 at 04:08
0

you can try like this.

setInterval(function(){
  if(div.textContent === '10') {alert('strike')}
}, 50);
Shabareesh
  • 25
  • 2