Why is the first "if" activated by itself when the second "else if" condition is met?

Basically, when the condition "event.target === checkbox && active" is met, the value of 'active' becomes "false". Therefore, the next click on the checkbox will satisfy the first condition "event.target === checkbox && !active", and that's what I want. However, what happens is that once the condition "event.target === checkbox && active" is met, and the code block is executed, the code block of the first "if" statement is also automatically executed. As a result, 'active' acquires the value "false" and then immediately regains the value of "true" again. This essentially prevents unchecking the checkbox if you click on it, which is something I don't want. Do you know how to prevent this from happening, and why does it happen in the first place?

There is the code:

function toggleSelectionMenu(checkbox, menu) {
  let active = false;
  document.addEventListener('click', function (event) {
    if (event.target === checkbox && !active) {
      checkbox.checked = true;
      menu.style.display = 'block';
      active = true;
      console.log(active);

    } else if (event.target !== checkbox && active || event.target === checkbox && active) {
      checkbox.checked = false;
      menu.style.display = 'none';
      active = false;
      console.log(active);
    }
  });
}

What I want is that the first click on the checkbox does what is described in the first "if" statement, and that the next click within the DOM executes what is stated in the following code block, regardless of whether the click is on the same checkbox or any other part of the DOM.

Upvotes: 0

Views: 48

Answers (1)

Barmar
Barmar

Reputation: 782165

The problem is that the else if condition is true whether or not event.target is checkbox. So when you click on an active checkbox, you'll toggle all the active checkboxes.

Separate the checking of event.target and active.

function toggleSelectionMenu(checkbox, menu) {
  let active = false;
  document.addEventListener('click', function (event) {
    if (!(event.target.nodeName == 'INPUT' && event.target.type == 'checkbox')) {
      // clicking outside any checkbox, uncheck it
      checkbox.checked = false;
      menu.style.display = 'none';
      active = false;
      console.log(active);
      return;
    }

    // not clicking on this checkbox, ignore
    if (event.target !== checkbox) {
      return;
    }

    // toggle the checkbox
    if (!active) {
      checkbox.checked = true;
      menu.style.display = 'block';
      active = true;
      console.log(active);
    } else {
      checkbox.checked = false;
      menu.style.display = 'none';
      active = false;
      console.log(active);
    }
  });
}

Upvotes: 0

Related Questions