I’m trying to make a count voter with percentage but the first click doesn’t register and makes the percentages NaN.
This is my code:
var pikaClick = 0;
var nineClick = 0;
var pikaPercent;
var ninePercent;
function getTotal() {
tClicks.innerHTML = parseInt(vPika.innerHTML) + parseInt(vNine.innerHTML);
pikaPercent = parseInt(vPika.innerHTML) / parseInt(tClicks.innerHTML) * 100;
vPika.innerHTML = pikaClick + " (" + pikaPercent.toFixed(2) + "%)";
ninePercent = parseInt(vNine.innerHTML) / parseInt(tClicks.innerHTML) * 100;
vNine.innerHTML = nineClick + " (" + ninePercent.toFixed(2) + "%)";
}
pika.onclick = function() {
pikaClick++;
getTotal();
}
nine.onclick = function() {
nineClick++;
getTotal();
}
<div>
<p> Pikachu Total Clicks : <span id="vPika"> 0 (0.00%) </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 (0.00%) </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>
Why does it do this and how do I fix it?
2
Answers
Since you already have variables storing all the counts, just use those instead of parsing the
innerHTML
of the elements in which you are displaying those counts.(Additionally, it is better to set
textContent
instead ofinnerHTML
since you don’t actually have to add new elements.)You are getting
NaN
because you settClicks.innerHTML
by using the values ofvPika.innerHTML
andvNine.innerHTML
but beforevPika
andvNine
are updated, so you end up dividing by0
initially.NaN
means “Not a number”. This can happen in certain circumstances:In your code, the
NaN
comes from an invalid math operation(0/0)
.Let’s look at it step by step.
pikaClick
is increased and is now onegetTotal
is calledNaN
One way to fix would be to try reordering some of the statements to ensure they get up to date information.
However, you can fix the problem and make your program simpler by simply using the internal variables themselves (instead of fetching information from the HTML).
Besides, you should generally avoid using
innerHTML
, as it can become a source for XSS vulnerabilities.Here is an example code that fixes the problem: