I have two buttons with a click counter each. I want to get the total number of clicks for those two but it's not working

Advertisements

I have two buttons with a click counter each. I want to get the total number of clicks for those two but it’s not working.

This is my code:

<div>
    <p> Pikachu Total Clicks : <span id="vPika"> 0 </span> </p>
    <img id="pika" src="https://img.pokemondb.net/sprites/ultra-sun-ultra-moon/normal/pikachu-f.png"/>
</div>

<div>
    <p> NineTails Total Clicks : <span id="vNine"> 0 </span> </p>
    <img id="nine" src="https://img.pokemondb.net/sprites/black-white/shiny/ninetales.png"/>             
</div>
<p> Overall Total Clicks : <span id="tClicks">  0 </span> </p>

<script>
var pikaClicks = 0;
var nineClicks = 0;

pika.onclick = function() {
    pikaClicks++;
    vPika.innerHTML = pikaClicks;
}

nine.onclick = function() {
    nineClicks++;
    vNine.innerHTML = nineClicks;
}

tClicks.innerHTML = parseInt(vPika.innerHTML) + parseInt(vNine.innerHTML);
</script>

I’ve tried different ways but the total still stays at zero

>Solution :

tClicks.innerHTML = parseInt(vPika.innerHTML) + parseInt(vNine.innerHTML); is only run once, when both values are 0. You need to explicitly update the content of the <span> containing the total on each click (in the event handlers).

const pika = document.getElementById("pika");
const nine = document.getElementById("nine");
const tClicks = document.getElementById("tClicks");
const vPika = document.getElementById("vPika");
const vNine = document.getElementById("vNine");
function updateTotal() {
    tClicks.textContent = pikaClicks + nineClicks;
}
pika.addEventListener('click', e => {
    vPika.textContent = ++pikaClicks;
    updateTotal();
});
nine.addEventListener('click', e => {
    vNine.textContent = ++nineClicks;
    updateTotal();
});

Leave a Reply Cancel reply