Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to set a timeout for a popup and close if user clicks elsewhere?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

.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 mousedown event listener to the whole document that invokes hide
    • Within hide, ensure that the click event’s target is not contained in the popup.
  • Set up the timeout to call hide
  • Important: Have hide clear 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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading