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

Modal Onclick Visibility Not Working As Intended

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:

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

    .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.

>Solution :

document.getElementsByClassName

The above returns a collection (an array of results, note the plural on getElement(s)). So you can’t just set the visibility directly on it.

Just by simply changing it to access the first index, it will work

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

But it would have been better if you used an ID instead, and access it by ID, which returns the same results.

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

Full snippet below.

function modalLogin() {
  var modal = document.getElementById("sign_in_modal");
  modal.style.visibility = "visible";
}
.modalSignin {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: black;
  min-width: 40%;
  min-height: 400px;
  visibility: hidden;
}
<div class="modalSignin" id="sign_in_modal"></div>

<div class="authBtns" onclick="modalLogin()">
  <a href="#" id="loginBtn">Login</a>
  <a href="#" id="regBtn">Register</a>
</div>
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