Reputation: 98
<script type="text/javascript">
function countdown(seconds, element)
{
var count = seconds;
var counter= setInterval(timer, 1000);
function timer()
{
count--;
if (count <= 0)
{
clearInterval(counter);
return;
}
element.innerHTML = "Seconds remaining: " + count;
}
}
</script>
<h1 onload="countdown(100, this)"></h1>
So why innerHTML of the calling tag doensn't change? I saw other codes, but i didn't see any error here. I'm newbie on JS coding.
Upvotes: 0
Views: 526
Reputation: 7368
onload
function can be used on <body
> tag, it doesn't seem to work on other tags. try adding it on <body>
function countdown(seconds, element)
{
var count = seconds;
var counter= setInterval(timer, 1000);
function timer()
{
count--;
if (count <= 0)
{
clearInterval(counter);
return;
}
element.innerHTML = "Seconds remaining: " + count;
//console.log(count);
}
}
h1List=document.getElementsByTagName("h1");
for(i=0;i<h1List.length;i++){
countdown(100-i*3, h1List[i]);
}
//countdown(100, document.getElementsByTagName("h1")[0]);
<h1></h1>
<h1></h1>
<h1></h1>
<h1></h1>
<!--<body onload="countdown(100,document.getElementsByTagName(`h1`)[0])">-->
Upvotes: 1
Reputation: 617
<script type="text/javascript">
function countdown(seconds)
{
var count = seconds;
var counter= setInterval(timer, 1000);
function timer()
{
count--;
if (count <= 0)
{
clearInterval(counter);
return;
}
document.getElementById("timer").innerHTML = "Seconds remaining: " + count;
}}
</script>
<body onload="countdown(100)">
<h1 id="timer"></h1>
</body>
check this one out if you want to run timer on page load event
Upvotes: 0