Reputation: 39
I created a popup that appears when I click a button, but to make it disappear I have to click again. Is there a way to set a timer and make it disappear?
This is the code:
// When the user clicks on div, open the popup
function myFunction() {
var popup = document.getElementById("myPopup");
popup.classList.toggle("show");
}
.popuptext {
display: none;
}
.popuptext.show {
display: block;
}
<div class="popup" onclick="myFunction()">Click me to toggle the popup!
<span class="popuptext" id="myPopup">A Simple Popup!</span>
</div>
Upvotes: 0
Views: 6063
Reputation: 637
This should work
function myFunction() {
var popup = document.getElementById("myPopup");
document.getElementById("myPopup").style.display= "block"
setTimeout(function(){
document.getElementById("myPopup").style.display= "none"
}, 3000);
}
Upvotes: 0
Reputation: 6747
I suggest you to read into the function setTimeout()
on w3schools or mozilla dev, which are both two great sites for programming beginners.
Your problem could be solved like shown in the following snippet:
function myFunction() {
var popup = document.getElementById("myPopup");
popup.classList.toggle("show");
if(popup.classList.contains("show")) // Check if the popup is shown
setTimeout(() => popup.classList.remove("show"), 10000) // If yes hide it after 10000 milliseconds
}
Upvotes: 3
Reputation: 380
<script>
// When the user clicks on div, open the popup
function myFunction() {
var popup = document.getElementById("myPopup");
popup.classList.toggle("show");
//Try this, setTimeout takes a callback function to be executed after an amount of time, in this case 3000 milliseconds is 3 seconds
setTimeout(function(){
popup.classList.toggle("show");
},3000)
}
</script>
Upvotes: 0
Reputation: 6446
I would use setTimeout:
function myFunction(el) {
var popup = document.getElementById("myPopup");
popup.classList.toggle("show");
setTimeout(() => {
popup.classList.remove("show");
}, 10000)
}
div {
display: none;
}
.show {
display: block !important;
}
<button onclick="myFunction()">Show div below</button>
<br/>
<div id="myPopup">No longer hidden</div>
Upvotes: 0