javascriptpopupshow

How can I close a popup when clicking another one?


I have a problem. I have a series of popups and I am not able to make the opened one closing when opening another. I'd like to have a result in which I open one of them and it closes when I open another. Here's a piece of my code:

<script>
    function popup0(){
        let popup = document.getElementById('popup0');
        popup.classList.toggle('show');
    }
</script>
<p class = 'popup' onclick = 'popup0()'>El Gringo
    <span class = 'popuptext' id = 'popup0'>
        Each time he loses a life point due to a card played by another player, Gringo draws a random card from the hand of that player (one card for each life).<br>(3 life points)
    </span>
</p><br>
<script>
    function popup1(){
        let popup = document.getElementById('popup1');
        popup.classList.toggle('show');
    }
</script>
<p class = 'popup' onclick = 'popup1()'>Willy the Kid
    <span class = 'popuptext' id = 'popup1'>
        During his turn, he can play any number of 'Bang!' cards.<br>(4 life points)
    </span>
</p><br>
<script>
    function popup2(){
        let popup = document.getElementById('popup2');
        popup.classList.toggle('show');
    }
</script>
<p class = 'popup' onclick = 'popup2()'>Lucky Duke
    <span class = 'popuptext' id = 'popup2'>
        Each time he is required to 'Draw!', he flips the top two cards from the deck and chooses the result he prefers. Both cards are discarded afterwards.<br>(4 life points)
    </span>
</p><br>
<script>
    function popup3(){
        let popup = document.getElementById('popup3');
        popup.classList.toggle('show');
    }
</script>
<p class = 'popup' onclick = 'popup3()'>Kit Carlson
    <span class = 'popuptext' id = 'popup3'>
        During Phase 1 of his turn, he looks at the top three cards of the deck, then chooses two to put into his hand and puts the remaining card back onto the deck, face down.<br>(4 life points)
    </span>
</p><br>

Solution

  • You can just create a new function to hide opened popups and call it inside each function.

    Like below:

        function hideOther(popupElem) {
      document.querySelectorAll('.popuptext:not(#'+popupElem+')').forEach(elem => {
        elem.classList.remove('show');
      });
    }
    
    function popup0() {  
      let popup = document.getElementById('popup0');
      hideOther('popup0');
      popup.classList.toggle('show');
    }
    

    You need to call hideOther inside each popup function like here we called it inside popup0

    Updated Passed current id to the function and checked to get only other popups to close