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 change visibility on div multiple times with javascript and css?

I have a popup in my app:

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

let modal = document.getElementById('modal')
modal.innerHTML = `
            <button class="close-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:

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

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?

>Solution :

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')
 } 
} 
 
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