Search code examples
javascriptcsssimplemodal

I can make a modal disappear, but I can't make it appear


I have this piece of code in JavaScript that tries to change the property in CSS "visibility: hidden;" for "visibility: none;" with a click of a button

const modal = document.getElementById('modal');
const button = document.getElementById('button');

button.addEventListener('click', function(){modal.style.visibility = "none";})

This code can make the modal disappear, but can't make it appear

Here it is the modal CSS properties:

#modal{
    margin: 5px 20px;
    padding: 20px 20px;
    position: absolute;
    top: 105px;
    right: 5px;
    width: 250px;
    height: 150px;
    background-color: lightgreen;
    border-radius: 10px;
    color: darkgreen;
    align-items: center;
    border: 4px solid darkgreen;
    visibility: hidden;
}

Solution

  • Visibility has 2 valid values:

    • hidden: Hide the element
    • visible: Show the element

    If you want your element to appear on-click: You need to change to use visible:

    button.addEventListener('click', function(){modal.style.visibility = "visible";})
    

    Furthermore, I suggest you use the display property instead:

    • block: Show the element
    • none: Hide the element

    Extra reading: What is the difference between visibility:hidden and display:none?