小能豆

Modal Onclick Visibility Not Working As Intended

javascript

My modal below isn’t working but I’m not experienced enough to figure why. I’m trying to hide my modal using visibility: hidden, then changing to visibility: visible onclick.

HTML

    <div class="modalSignin"></div>

     <div class="authBtns" onclick="modalLogin()">
          <a href="#" id="loginBtn">Login</a>
          <a href="#" id="regBtn">Register</a>
     </div>

CSS:

    .modalSignin {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background-color: black;
        min-width: 40%;
        min-height: 400px;
        visibility: hidden;
    }

JAVASCRIPT:

   function modalLogin() {
        var modal = document.getElementsByClassName("modalSignin");
         modal.style.visibility = "visible";
    };

Please see above code snippets.


阅读 58

收藏
2023-12-21

共1个答案

小能豆

The issue in your JavaScript code is that getElementsByClassName returns a collection of elements (even if there’s only one element with that class). Therefore, you need to access the first element in the collection to modify its style.

Here’s the corrected JavaScript code:

function modalLogin() {
    var modal = document.getElementsByClassName("modalSignin")[0];
    modal.style.visibility = "visible";
}

Now, the [0] at the end of getElementsByClassName("modalSignin") ensures that you are accessing the first (and in this case, the only) element with the class “modalSignin”.

Additionally, if you want to hide the modal again, you can modify the modalLogin function to toggle between “visible” and “hidden” based on the current visibility:

function modalLogin() {
    var modal = document.getElementsByClassName("modalSignin")[0];
    modal.style.visibility = (modal.style.visibility === "visible") ? "hidden" : "visible";
}

This way, each click on the “authBtns” will toggle the visibility of the modal.

2023-12-21