Page 1 of 1
Countdown function
Posted: Mon Nov 16, 2009 12:32 pm
by Haddman
I've been working on a small countdown function but I don't seem to be able to get it to work:
Code: Select all
function tick_timer() {
var tick;
tick = document.getElementById('tick').value;
tick -= 1;
document.getElementById('tick').innerHTML = tick;
}
setTimeout("tick_timer()",1000);
Code: Select all
<span id="tick"><?=counter("2");?></span>
EDIT: When the script runs it returns "NaN"
I have a feeling that this is a very simple thing to fix but I'm a newbie when it comes to Javascript.
Re: Countdown function
Posted: Mon Nov 16, 2009 12:55 pm
by akuji36
Re: Countdown function
Posted: Mon Nov 16, 2009 1:00 pm
by Haddman
That's a whole different thing and something i could i accomplish in PHP, I'm trying to make a live counter not something that runs once everytime the page loads.
Thanks anyways

Re: Countdown function
Posted: Mon Nov 16, 2009 6:05 pm
by califdon
I believe that a <span> element doesn't have a Value property, so it's NaN (Not a Number). Try it with an <input> element and it will probably work.
Re: Countdown function
Posted: Tue Nov 17, 2009 6:20 am
by iankent
califdon wrote:I believe that a <span> element doesn't have a Value property, so it's NaN (Not a Number). Try it with an <input> element and it will probably work.
Correct

Your solutions to the problem are as califdon says to use a hidden input, e.g.
Code: Select all
<input id="abc" value="1" />
<script>
var result = document.getElementById("abc").value - 1;
alert(result);
</script>
or alternatively, use parseInt/parseFloat, e.g.
Code: Select all
<span id="abc">1</span>
<script>
var result = parseInt(document.getElementById("abc").innerText) - 1;
alert(result);
</script>
hth
Re: Countdown function
Posted: Tue Nov 17, 2009 6:53 am
by Haddman
Shouldn't <div> work? I tried that but the same error.
Re: Countdown function
Posted: Tue Nov 17, 2009 6:59 am
by iankent
Haddman wrote:Shouldn't <div> work? I tried that but the same error.
<div> will also work on the same principle as <span>, i.e.
Code: Select all
<div id="abc">1</div>
<script>
var result = parseInt(document.getElementById("abc").innerText) - 1;
alert(result); /* should display 0 */
</script>
as califdon said, the only element that has a value is an input, everything else you'll need to use innerText and parseInt/parseFloat to get the value
hth
Re: Countdown function
Posted: Wed Nov 18, 2009 11:58 am
by Haddman
Got it working, thanks for the help.