So I have this button which onclick has a function that shows an element. Now I want to add a function by default that will hide this same element after some given interval. So if I click this button, div-container will be displayed after .5s. Now I want to check that if this div-container is displayed, the users can read it and then it will be hidden. So It's more like an alert.
Heres my snippet:
document.getElementById("mybtn").addEventListener("click",function(){
let clock = setInterval(() => {
clearInterval(clock)
clock = null
document.getElementById('alert').style.display = 'block'
}, 500)
})
// this is where I tried to make it hide after some given interval but it's not working
var alert = document.getElementById('alert');
if(alert.style.display==="block"){
let clock = setInterval(() => {
clearInterval(clock)
clock = null
document.getElementById('alert').style.display = 'none'
}, 500)
}
<button id="mybtn">Show/hide</button>
<div id="alert" style="display:none"><h3>this is an alert</h3></div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
I think you are looking for setTimeout
.
let clockTimeout = null
document.getElementById("mybtn").addEventListener("click",function(){
document.getElementById('alert').style.display = 'block'
clearTimeout(clockTimeout)
clockTimeout = setTimeout(() => {
document.getElementById('alert').style.display = 'none'
}, 1500)
})
<button id="mybtn">Show/hide</button>
<div id="alert" style="display:none"><h3>this is an alert</h3></div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
Inside your event you have first to show the alert div container. then you set the Timeout. inside the timeout function you hide the alert box again.
document.getElementById("mybtn").addEventListener("click",function(){
document.getElementById('alert').style.display = 'block'
let clock = setInterval(() => {
document.getElementById('alert').style.display = 'none'
}, 5000)
})
<button id="mybtn">Show/hide</button>
<div id="alert" style="display:none"><h3>this is an alert</h3></div>
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>