JS event listeners conflicting with PHP form action

I am trying to make a login form that pops up when the user clicks login, but closes when the user clicks outside of the form. The login should be handled via a PHP script.
As it is now, when I click the login button on the form, nothing happens. I know the script works because when I get rid of all the fancy JS effects, the login works.
So my question is, how can I have it all? Is there a work around, or should I try to find a different method of closing the window?

<button onClick = loginMenu() id='login-button'>
                <i class="fas fa-user-circle"></i>
</button>
<div class="form" id='login-menu'>
    <div class='modal'>
        <form action="test.php" method="post">
            <input type="text" name="username" placeholder="username = lib" id="username" required/>
            <input type="password" name="password" placeholder="password = 123" id="password" required/>
            <button type="submit">login</button>
        </form>
    </div>
</div>
function loginMenu() {
  let modalRoot = document.getElementById("login-menu");
  let button = document.getElementById("login-button");
  let modal = document.querySelector(".modal");

  modalRoot.addEventListener("click", rootClick);
  button.addEventListener("click", openModal);
  modal.addEventListener("click", modalClick);

  function rootClick() {
    modalRoot.classList.remove("visible");
  }

  function openModal() {
    modalRoot.classList.add("visible");
  }

  function modalClick(e) {
    e.preventDefault();
    e.stopPropagation();
    e.stopImmediatePropagation();
    return false;
  }
}

here’s the codepen I took this from
These are just snippets I have a head, link to JS script, etc. in the full version.

I’ve solved it myself. The issue was with the event bubbling. I will post the code in case any one finds this post via Google.

let modalRoot = document.getElementById("login-menu");
function loginMenu() {
  let button = document.getElementById("login-button");
  button.addEventListener("click", openModal);

  function openModal() {
    modalRoot.classList.add("visible");
  }
}

loginMenu();

window.addEventListener("click", function(e) {
  if (
    !document.getElementById("login-button").contains(e.target) &&
    !document.getElementsByClassName("modal")[0].contains(e.target)
  ) {
    modalRoot.classList.remove("visible");
  }
});

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.