Marcos Molina
Marcos Molina

Reputation: 39

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?

Upvotes: 0

Views: 148

Answers (1)

Lu&#237;s Ramalho
Lu&#237;s Ramalho

Reputation: 10208

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>

Upvotes: 1

Related Questions