0

I am trying to make a button add an amount of points to another variable and then displaying the value of the variable as a score, but I cant seem to get it working.

I tried doing the following script but whenever I try to test it, the whole score variable disappears and i don't know what to do

<button onclick="addPoints25()">done</button>
<p id="counter"></p>

<script>

var points = 0;
document.getElementById("counter").innerHTML = points;

function addPoints25() {
    
    var points + 25;
}
</script>

3 Answers3

1

You have to just get the element of your counter once.

Edited: so that the code works with localstorage

Check Addition_assignment for more details of how to concatenate/sum values

    //uncomment the next line to clear the localStorage
    //window.localStorage.clear();
    const counter = document.getElementById("counter");//get element
    let points = Number(localStorage.getItem(0));//declare var
    counter.textContent=points;//initial value set

    function addPoints25() {
        points += 25;//sum value
        window.localStorage.setItem(0, points);//update value in index 0 for the value of points variable
        //console.log(points);//for debugging purposes
        counter.textContent=localStorage[0];//update value in element
    }
Chris G
  • 1,598
  • 1
  • 6
  • 18
1

You need to update the textContent of the element when calling the function:

const counter = document.getElementById("counter");
let points = 0;

counter.textContent = points;

function addPoints25() {
  points += 25;
  counter.textContent = points;
}
<button onclick="addPoints25()">done</button>
<p id="counter"></p>

* Note the use of const and let instead of var and textContent instead of innerHTML

UPDATE

The asker wants to store the points. This can be done different ways. One of them is via localStorage:

const counter = document.getElementById("counter");
let points = Number(localStorage.getItem('points'));

counter.textContent = points;

function addPoints25() {
  points += 25;
  localStorage.setItem('points', points)
  counter.textContent = points;
}
<button onclick="addPoints25()">done</button>
<p id="counter"></p>
ericmp
  • 1,163
  • 4
  • 18
1

If you are trying to increase or add a fixed amount of number on each button click then you can try this:-

<button onclick="addPoints25()">done</button>
<p id="counter"></p>

<script>
let points = 0;
let scoreBoard = document.getElementById("counter")
scoreBoard.textContent = 0
function addPoints25(){
   points += 25;
   scoreBoard.textContent = points;
}
</script>
M Hasan
  • 19
  • 4