Reputation: 1092
I am building a interstitial page, using <div> and JavaScript, really simple script but neat.
Everything is working, but I also would like to close the div's after a few seconds (like 10 seconds, for example). Here what I have so far:
To load the div's I have a onload function like this:
onload="document.getElementById('div1').style.display='block';document.getElementById('div2').style.display='block'"
To hide the divs I have an onclick function like this:
<a href = "javascript:void(0)" onclick = "document.getElementById('div1').style.display='none';document.getElementById('div2').style.display='none'"></a>
How can I execute the onclick function with a timer, and how can I do it? It also has to be in JavaScript.
Upvotes: 85
Views: 206214
Reputation: 51451
I believe you are looking for the setTimeout function.
To make your code a little neater, define a separate function for onclick in a <script>
block:
function myClick() {
setTimeout(
function() {
document.getElementById('div1').style.display='none';
document.getElementById('div2').style.display='none';
}, 5000);
}
then call your function from onclick
onclick="myClick();"
Upvotes: 141
Reputation: 5533
setTimeout will help you to execute any JavaScript code based on the time you set.
Syntax
setTimeout(code, millisec, lang)
Usage,
setTimeout("function1()", 1000);
For more details, see http://www.w3schools.com/jsref/met_win_settimeout.asp
Upvotes: 15
Reputation: 222158
onclick = "setTimeout(function() { document.getElementById('div1').style.display='none';document.getElementById('div2').style.display='none'}, 1000)"
Change 1000 to the number of milliseconds you want to delay.
Upvotes: 5