Open modal and close the other

Asked

Viewed 44 times

1

I need help that by clicking on a name open the screen to send messages, and by clicking on another name close the previous window and open the new one and so on

<li><a href="javascript:void(0)" id="user" class="class_1">Fulano 01</a></li>

<li><a href="javascript:void(0)" id="user" class="class_2">Fulano 02</a></li>`

<li><a href="javascript:void(0)" id="user" class="class_3">Fulano 03</a></li>

function modal(modalID){
    const modal = document.getElementById(modalID);
    if (modal) {
        modal.classList.add('open');
        modal.addEventListener('click', (e) => {
            if (e.target.id == modalID) {
                modal.classList.remove('open');
            }
        });
        console.log(modal, e.target.id);
 }
}

pull the bank id and call the function to open the windows

const class_<?php echo $list['id'];?> = document.querySelector('.class_<?php echo $list['id'];?>');

class_<?php echo $list['id'];?>.addEventListener('click', () => modal('id_<?php echo $list['id'];?>'));


<div id="id_1" class="modal">1</div>
<div id="id_2" class="modal">2</div>
<div id="id_3" class="modal">3</div>

<style>
  .modal {display: none;}
  .modal.open {display: block;}
</style>

1 answer

1


From what I understood from your code, if you declare the variable "modal" outside your function, you can close without problem.

var modal;

function modal(modalID){
    if(modal) {
        modal.classList.remove('open');
    }
    modal = document.getElementById(modalID);
    if (modal) {
        modal.classList.add('open');
        modal.addEventListener('click', (e) => {
            if (e.target.id == modalID) {
                modal.classList.remove('open');
            }
        });
        console.log(modal, e.target.id);
    }
}
  • how so if(modal) {&#xA; modal.classList.remove('open');&#xA; } did not understand this part, closes the modal before opening

  • Yes, to close the previous modal before opening the new, as you said q want to do.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.