It looks like you're trying to check if the click event raised an object with the dropbtn class.
If you use jQuery, you can do the same:
function myFunction() { document.getElementById("myDropdown").classList.toggle("show"); } // Close the dropdown menu if the user clicks outside of it window.onclick = function(event) { if (!$(event.target).hasClass('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'); } } } }
If you are not using jQuery, you can get the class name and then check if dropbtn is one of them.
function myFunction() { document.getElementById("myDropdown").classList.toggle("show"); } // Close the dropdown menu if the user clicks outside of it window.onclick = function(event) { var classes = event.target.className.split(' '); var found = false; var i = 0; while (i < classes.length && !found) { if (classes[i]=='dropbtn') found = true; else ++i; } if (!found) { 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'); } } } }
source share