Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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();
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading