简体   繁体   中英

How to close a popup when clicking on another one?

I have a list of buttons that show a popup like a tooltip when clicking on it and closes it when you click again.

I am looking for: when you click one of those button, any popup opened before automatically closes with no need of clicking again on it.

function myFunction2() {
    var popup = document.getElementById("myPopup2");
    popup.classList.toggle("show");
    }
function myFunction3() {
    var popup = document.getElementById("myPopup3");
    popup.classList.toggle("show");
    }

One simple way to do that will be toggling the class on every element(popup) at the same time.

For simplicity, you can also assign the same class to each popup.

example:

function myFunction() {
    var popups = document.getElementsByClassName("myPopup");
    for( var i = 0 ; i< popups.length; i++) {
      popups[i].classList.toggle("show");
    }
}

Apply a class (let's call it " btns ") to all buttons (supposing that you're using the <button> tag) and try doing the following :

function myFunction() {
    var popup = document.getElementById("myPopup");

    if (document.querySelectorAll("button.btns").style.display = "block") {
        document.querySelectorAll("button.btns").style.display = "none";
        &&
        popup.classList.toggle("show");
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM