I have made this script and I design it in a way when you click any where outside of the div the div should disappear but I notice that when you click on the div it self it disappear as well. How can I prevent that from occurring I only want it to work by clicking any where out side the div to make the div disappear not by clicking on the div to make it disappear as well. So i'm trying to prevent that. How can I do that? And I still want the toggle affect on the button as well.
document.addEventListener('DOMContentLoaded', function() {
var bx = document.getElementsByTagName('button')[0];
bx.addEventListener('click', fx);
function fx() {
document.getElementById("myDropdown").classList.toggle("show");
}
window.onclick = function(event) {
if (!event.target.matches('.dropbtn')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
});
.dropdown-content {
display: none;
}
.show {
display: block;
}
<button class="dropbtn">Dropdown</button>
<div id="myDropdown" class="dropdown-content">
<h1>hello</h1>
<img src='http://full.creative.touchtalent.com/The-enchanted-forest-97329.jpg'>
</div>
Your window.onclick
handler only checks to see if you clicked the button, not inside the <div>
. Include the <div>
check in your condition:
if (!event.target.matches('.dropbtn') && !event.target.closest('.dropdown-content')) {
Element.closest
returns null
if the element does not match and is not a descendant of an element that matches its argument.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments