0

According to the chrome console there are no problems however there are as my variable is "undefined" despite it being set as "0"

I have used the following resources: Resource 1 Resource 2

I am trying to make it so when the user clicks my image it will add +1 to the points variable (Game.points) here is my code (for context purposes):

<!DOCTYPE html>

<script>
function Game() {
var points = "0"
document.getElementById("myText").innerHTML = Game.points;

}
</script>
<center>  <img onclick="Game.points = Game.points + 1" src="https://static.wikia.nocookie.net/villains/images/5/5d/Frieza.png/revision/latest?cb=20200625063534" width="350px"> </center>
<body onload="Game()">

    <h1>"The value for number is: " <span id="myText"></span></h1>
ethry
  • 731
  • 6
  • 17

1 Answers1

2

The points variable is not a member of the Game object. To reference it, just use the points keyword.

There's also a couple of changes you can make to improve the code quality:

  • Remove the inline onclick and onload attributes. They are outdated and not good practice. Use addEventListener() to bind events within JS, instead of HTML.
  • Set points to be a numeric value, not a string. This way there's no type coercion needed when you increment its value.
  • Put any CSS styling in a separate stylesheet, not the HTML

const myText = document.querySelector('#myText');
const img = document.querySelector('img');
let points = 0;

document.addEventListener('DOMContentLoaded', () => {
  updateText();
});

img.addEventListener('click', () => {
  points++;
  updateText();
});

updateText = () => {
  myText.textContent = points;
};
img {
  width: 350px;
}
<center>
  <img src="https://static.wikia.nocookie.net/villains/images/5/5d/Frieza.png/revision/latest?cb=20200625063534" />
</center>

<h1>
  The value for number is: 
  <span id="myText"></span>
</h1>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339