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.
Aucun commentaire:
Enregistrer un commentaire