I have this tooltip info panels that show up and hide when you click on an icon. I wanted them to close too when you click anywhere else but the icon, as seems natural.
I've done something that works, but ONLY for the first tooltip of the page. I got several and when trying to loop the behavior it just won't do it and I'm not sure what I'm missing.
Here's what I have
// Dropdown to show or hide tooltip
var dropdownButton = document.getElementsByClassName("dropdown__btn");
for (i = 0; i < dropdownButton.length; i++) {
// Action when clicking
dropdownButton[i].addEventListener("click", function() {
/* Toggle between hiding and showing the active panel */
var panel = this.nextElementSibling;
if (panel.classList.contains("is-hidden")) {
panel.classList.remove("is-hidden");
} else {
panel.classList.add("is-hidden");
}
});
// Closes when clicked anywhere else
// Only works with the first one, though it logs the message for each one
window.addEventListener('click', function(e) {;
if (!dropdownButton[i].contains(e.target)) {
console.log("you're NOT clicking the btn");
dropdownButton[i].nextElementSibling.classList.add("is-hidden");
}
e.stopPropagation();
});
}
.is-hidden {
display: none;
}
<p class="dropdown__btn">x</p>
<div class="dropdown__panel is-hidden">
<p>Renew automatically on every expiration date.</p>
</div>