I created a dropdown menu, which is activated and closed by setting display to block or none, depending on the state of a checkbox.
Everything is working as it is supposed to, but I want the menu to close when I click on the checkbox, which works by default or when I click anywhere else, which also works with my script.
BUT: I am not able to accomplish both. My script works fine, but then I am unable to close the menu by clicking on the checkboxes label.
window.onclick = function(unchceck) {
let button = document.getElementById("toggle_button");
if (unchceck.target != button) {
button.checked = false;
}
}
/* highly simplified version of the CSS, just to show the function */
.expM {
display: none;
}
#toggle_button {
display: none
}
#toggle_button:checked~.expM {
display: block;
}
li {
background-color: rgb(70, 70, 70);
}
<!-- my checkbox with a label, the checkbox is set to display: none -->
<input type="checkbox" name="test" id="toggle_button">
<label for="toggle_button">
<img id="menuBurger" src="https://picsum.photos/20"/>
</label>
<!-- simplyfied version of my menu -->
<ul class="expM">
<li><a class="menuLink" href="index.html">Home</a></li>
<li><a class="menuLink" href="pages/GetStarted.html">Get Started</a></li>
</ul>
I tried multiple solutions, but none them worked. They resulted in me not being able to check the checkbox anymore or in the original premisse, that I was only able to achieve one of the two ways to uncheck the box.
Some things I tried were setting a cooldown/ timeout for the checkbox, which also did not work. I also tried to stop the function as soon, as checked
= false
, which worked neither.
You would help me a lot with a clean solution, making it possible to close the menu by clicking on the checkbox and by clicking anywhere on the screen.
3
Answers
i think the problem is:
u click the checkbox lable -> the checkbox deactivates itself and the script activates it again because its checking if only the checkbox isnt clicked.
so use this to fix it:
(add an id to your img and replace "YOUR IMG ID HERE" with the img id)
Code for closing your "menu" for any click outside it, without disturbing the checkBox click event :
PS: your code was close but you neglected to deal with bubbles events
If I understood correctly, the OP needs the menu to close/open according to the associated checkbox status (unchecked/checked), and in addition should the user click outside of the menu, then the default behavior is to uncheck the checkbox. The solution provided works for one or more menus, details are commented in the example.