I am facing an issue with my code. I want to close the dropdown menu when clicking outside of it or on the items within the dropdown. How can I achieve this?
I attempted to use
addEventListener('click', myFunction)
on `document` but it did not work as expected. I also looked for solutions on Stack Overflow, but most of them involved jQuery. Can someone help me fix this issue?
.block {
display: block !important;
}
<div class="dropdown" style="position: relative;display: inline-block;">
<button class="dropbtn" onclick="dropdown()" style="padding: 16px;font-size: 16px;border: none;cursor: pointer;">Dropdown</button>
<div class="dropdown-content" id="dropdown" style="display: none;position: absolute;min-width: 160px;box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);z-index: 1;">
<a href="#" style="color: black;padding: 12px 16px;text-decoration: none;display: block;">Yes</a>
<a href="#" style="color: black;padding: 12px 16px;text-decoration: none;display: block;">No</a>
</div>
</div>
<script type="text/javascript">
function dropdown() {
document.getElementById("dropdown").classList.add("block");
}
</script>
If I use the following code, the dropdown menu doesn't even open:
document.addEventListener("click", myFunction);
function myFunction(){
document.getElementById("dropdown").classList.remove("block");
}
Thank you for your attention :)