I have looked around at similar posts and seem to have hit a snag in how the javascript around this implementation works. I have a dropdown with a filter where I click a button to initiate the dropdown. This works fine. However, it seems the only way to dismiss this dropdown is to click the original button. I'm trying to dismiss when clicking anywhere else on the screen other than the dropdown. I'm not sure if the way I have approached this is a quirk with javascript, but the following code sets out my approach and on a conceptual level I think this should work fine:
Code:
function myFunction() {
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');
}
}
}
}
function filterFunction() {
var input, filter, ul, li, a, i;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
div = document.getElementById("myDropdown");
a = div.getElementsByTagName("a");
for (i = 0; i < a.length; i++) {
if (a[i].innerHTML.toUpperCase().indexOf(filter) > -1) {
a[i].style.display = "";
} else {
a[i].style.display = "none";
}
}
}
<div class="dropdown">
<button onclick="myFunction()" class="dropbtn"><img src="bread.png" height="50" width="50" style="vertical-align:middle" align="left"><a>Testing</a></button>
<div id="myDropdown" class="dropdown-content">
<input type="text" placeholder="Search.." id="myInput" onkeyup="filterFunction()">
<a> Dropdown Content 1 </a>
<a> Dropdown Content 2 </a>
<a> Dropdown Content 3 </a>
</div>
</div>
Thanks in advance and have a great day out there!