Home > Net >  How to change visibility on div multiple times with javascript and css?
How to change visibility on div multiple times with javascript and css?

Time:11-05

I have a popup in my app:

<div id="modal"></div>

let modal = document.getElementById('modal')
modal.innerHTML = `
            <button  onclick="close_modal()">Close</button>
        `

#modal{
        width: 30em;
        height: 24em;
        overflow: hidden;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        visibility: hidden;
    }

When I click certain button function is triggered which has modal.classList.add('open-modal') in it.

.open-modal{
        visibility: visible !important;
    }

close_modal function is:

function close_modal(){
        modal.classList.add('close-modal')
    }

CSS:

.close-modal{
        visibility: hidden !important;
    }

It works just fine once(i can open and close popup but when I try to open it second time it doesn't. Why is this happening and how to fix it?

CodePudding user response:

After adding a new class, you must remove the previous class from the element's classlist. So the modal won't seem to work anymore after having both classes at the same time.

for ex.

function changeVisibility(modal) {
 if(modal.classList.contains('open-modal')) {
   modal.classList.remove('open-modal');
   modal.classlist.add('close-modal');
 } else {
    modal.classList.remove('close-modal');
    modal.classList.add('open-modal')
 } 
} 
 

CodePudding user response:

If your trying to do modals, you should use HTML's <dialog> element (Also see HTMLDialogElement). MDN has a tutorial on it.

  • Related