I have the below code. How I can close the dropdown when clicking the outer space or items of that?
I tried by addEventListener('click', myFunction) over `document but it not works. Also, I search questions of the stack, but more are about solutions with jquery. How to fix it?
.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 below code, so even the dropdown does not open.
document.addEventListener("click", myFunction);
function myFunction(){
document.getElementById("dropdown").classList.remove("block");
}
Thanks for your attention:)
With your appraoch, it will close everytime any thing on the document is clicked. You do not want that.
Listen for onclick on the document, but exclude the scenario when it is clicked inside your box:
.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");
}
document.addEventListener("click", myFunction);
function myFunction(){
if (!document.getElementsByClassName('dropdown')[0].contains(event.target)){ document.getElementById("dropdown").classList.remove("block");
}
}
</script>