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.
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.
getElementsByClassName
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”.
[0]
getElementsByClassName("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:
modalLogin
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.