views:

119

answers:

3

Why wont it countdown?

<script language="JavaScript" TYPE="text/javascript">
var container = document.getElementById('dl');
var seconds = 10;
var timer;
function countdown() {
seconds--;
if(seconds > 0) {
    container.innerHTML = 'Please wait <b>'+seconds+'</b> seconds..';
} else {
    container.innerHTML = '<a href="download.php">Download</a>';
    clearInterval(timer);
}
}
timer = setInterval(countdown, 1000);
</script>

<div id="dl"></div>
<input type="button" onclick="setInterval(countdown, 1000);" id="dl" value="Download" />
+3  A: 

Try to move the <script> block after the <div id="dl"></div>.


This way, when document.getElementById('dl'); is executed, the corresponding element in the page will already exist.

With what you posted, when document.getElementById('dl'); is executed, the corresponding <div> is not there yet -- and, so, cannot be found.

Pascal MARTIN
or wrap it in a callback that runs on page loaded, e.g., in jQuery `$(function() { ...your code here });`
tvanfosson
That would probably be a better solution, yes -- and it would allow things not have *local* variables, to no pollute the global namespace.
Pascal MARTIN
A: 

Because you are trying to reach the element before it exists, as the code runs before the element is loaded.

Move the line that locates the element inside the function:

<script type="text/javascript">

var seconds = 10;
var timer;

function countdown() {
  var container = document.getElementById('dl');
  seconds--;
  if(seconds > 0) {
    container.innerHTML = 'Please wait <b>'+seconds+'</b> seconds..';
  } else {
    container.innerHTML = '<a href="download.php">Download</a>';
    clearInterval(timer);
  }
}

timer = setInterval(countdown, 1000);

</script>

<div id="dl"></div>
<input type="button" onclick="setInterval(countdown, 1000);" id="dl" value="Download" />
Guffa
A: 

setInterval takes a string to execute, not a function pointer

timer = setInterval("countdown()", 1000);

JoeNathan
This is wrong. You *can* pass a string, but it's not considered a good idea. You can definitely pass a function pointer.
Pointy