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?
Function:
// When the user clicks on div, open the popup
function myFunction() {
var popup = document.getElementById("myPopup");
popup.classList.toggle("show");
}
Style:
.popuptext {
display: none;
}
.popuptext.show {
display: block;
}
The HTML:
<div class="popup" onclick="myFunction()">Click me to toggle the popup!
<span class="popuptext" id="myPopup">A Simple Popup!</span>
</div>
I need the popup to close after 10 seconds OR when the user clicks somewhere else.
I edited the code to below and it does close after 10 seconds, how to achieve the second part (close when user clicks somewhere else):
function myFunction() {
var popup = document.getElementById("myPopup");
popup.classList.toggle("show");
if(popup.classList.contains("show"))
setTimeout(() => popup.classList.remove("show"), 10000)
}
>Solution :
To do this you need to:
- Define a function,
hide()that hides the popup. - Add an
mousedownevent listener to the wholedocumentthat invokeshide- Within
hide, ensure that the click event’stargetis not contained in the popup.
- Within
- Set up the timeout to call
hide - Important: Have
hideclear the created timeout and remove the listener that was added.
function myFunction() {
var popup = document.getElementById("myPopup");
popup.classList.add('show')
let timeout;
function hide(e) {
if (popup.contains(e.target)) return;
popup.classList.remove("show");
document.removeEventListener('mousedown', hide);
clearTimeout(timeout)
}
document.addEventListener('mousedown', hide)
timeout = setTimeout(hide, 10000)
}
.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>