Reputation: 15
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" />
Upvotes: 1
Views: 2411
Reputation: 1
The setInterval
takes a string to execute, not a function pointer.
timer = setInterval("countdown()", 1000);
Upvotes: -2
Reputation: 700152
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" />
Upvotes: 1
Reputation: 400912
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.
Upvotes: 4