JavaScript 'score counter' to work across various pages on website

I’m trying to ‘gamify’ my website to engage learners. I am still incredibly new to JavaScript so I apologize in advance. There are dozens of similar articles, but none that match my needs closely and I have tried and failed to implement a fix with other similar questions – sorry (I have tried hard!)

Across approximately 10 pages, inside the navbar, I want to insert a counter. The code below is using the ID ‘score-counter’ to do this, and I’ve tried using localStorage to retain the score of that learner across each page. I’ve managed to get it to work (somewhat) but instead of adding 10 to the original value, it’s creating an entirely new counter and starting from scratch.

I want each button to only be clickable once (per page refresh) so I have tried to remove the eventListener after each button is clicked. I also want a straight-forward way to add more buttons to the counter system, so I’ve tried to keep it to the two simple classes ‘increment-button’ and ‘first-click’.

<button class="first-click increment-button">Add 10 to the value!</button>
<div id="score-counter">0</div> <!-- DISPLAYS THE COUNT -->
let score = localStorage.getItem("score") || 0;
const incrementButtons = document.querySelectorAll(".increment-button");
const scoreCounter = document.getElementById("score-counter");
scoreCounter.textContent = score;

for (let button of incrementButtons) {
    button.addEventListener("click", function(){
        if(this.classList.contains("first-click")) {
            score += 10;
            localStorage.setItem("score", score);
            this.classList.remove("first-click");
        }
    });
}

The output currently keeps doing this: 201010101010

It’s saving the output successfully, but instead of adding a value of 10 to the original score, it’s creating a whole new score and starting from 0 again. Does this make sense?

I’ve tried changing the JavaScript to count up from the value of 0

let score = localStorage.getItem("score") || 0;

I’ve also tried tweaking the score value

        if(this.classList.contains("first-click")) {
            score = scoreCounter + 10;

I’ve tried looking through various StackOverflow and other web resources for similar problems but have struggled to found any answer that fits what I’m trying to achieve. Can anyone offer any advice? Thanks in advance!

>Solution :

You need to convert the string you get from localStorage.getItem to a number. This can be done with the unary plus operator.

let score = +localStorage.getItem("score") || 0;

Leave a Reply