Search code examples
javascriptevent-handlingclickdom-eventsevent-listener

Why click event works after two clicks VANILLA


I am trying to trigger a function through a event listener with only one click. But it occurs after two click (in the first time) if I don't do F5 its trigger after one click.

Code:

HTML

    <div class="main-header-navbar">
   ....
        <span class="main-header-navbar-right-icons">
            <i class="fas fa-search header-icon"></i>
            <i class="fas fa-plus header-icon"></i>
        </span>
    </div>

JS

const ADD_FORM_BUTTON = document.querySelector(".fa-plus");
ADD_FORM_BUTTON.addEventListener("click", function (event) {
    event.preventDefault();
    if (ADD_FORM.style.display === "none") {
        ADD_FORM.style.display = "flex";
    } else ADD_FORM.style.display = "none";
});

What am I missing?


Solution

  • You probably need to add style="display: none;" to your ADD_FORM so that it's initially hidden, then when you click on the fa-plus it will display it. See the snippet below:

    const ADD_FORM_BUTTON = document.querySelector(".fa-plus");
    const ADD_FORM = document.getElementById("form");
    
    ADD_FORM_BUTTON.addEventListener("click", function(event) {
      event.preventDefault();
      if (ADD_FORM.style.display === "none") {
        ADD_FORM.style.display = "flex";
      } else {
        ADD_FORM.style.display = "none"
      };
    });
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css" rel="stylesheet" />
    
    <div class="main-header-navbar">
      <span class="main-header-navbar-right-icons">
        <i class="fas fa-search header-icon"></i>
        <i class="fas fa-plus header-icon"></i>
      </span>
      <div id="form" style="display: none;">ADD_FORM</div>
    </div>