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.
The problem is that the
else ifcondition is true whether or notevent.targetischeckbox. So when you click on an active checkbox, you'll toggle all the active checkboxes.Separate the checking of
event.targetandactive.