Question

var num = Math.floor(document.getElementById("num").innerHTML);
document.getElementById("num").innerHTML = num+1;
}
else{
document.getElementById("num").innerHTML = num-1;
}

I get $NaN, unfortunately!

The contents of the span is <span id="num">0</span>, you know, nothing special, and I must be doing something stupid so I'm utterly confused!

Thank ye.

Was it helpful?

Solution

And your full code shows why -1 does not work

if (document.getElementById("div").style.top === "40px") {
    var num = Math.floor(document.getElementById("num").innerHTML);
    document.getElementById("num").innerHTML = num + 1;
} else {
    document.getElementById("num").innerHTML = num - 1;
}

So what is undefined - 1? Well it is NaN! Why? because num is set in the if, not the else.

How do you fix it? Move the var num line outside of the if!

OTHER TIPS

.innerHTML returns a string. Strings can't be .floored. You'll have to parseInt() first.

The shown code is incomplete and makes it impossible to track. But I'm assuming that the NaN is being passed to Floor() to begin with. Pass a valid number/numeric string to floor() to make it work. Error is in the logic of code not shown in the question.

EDIT:

After looking at your code it's clear that the problem is due to a misplaced assignment operation. If the 'if' part is called, everything is fine, but if the 'else' part is called, 'num' is never created or assigned a value, causing it to be NaN. To fix this issue I'd recommend doing this:

Change this:

if(document.getElementById("div").style.top === "40px"){
    var num = Math.floor(document.getElementById("num").innerHTML);
    document.getElementById("num").innerHTML = num+1;
}
else{
    document.getElementById("num").innerHTML = num-1;
}

To this:

var num = Math.floor(document.getElementById("num").innerHTML);
if(document.getElementById("div").style.top === "40px"){
    document.getElementById("num").innerHTML = num+1;
}
else{
    document.getElementById("num").innerHTML = num-1;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top