I’m currently trying to close an element when its style is different than “display = none”. I’m having an error in the console telling me that lists. some aren’t a function so I may not have understood well the “some” method.
More Infos on what I want : Given that I have 3 lists (in lists), when I click outside of it or its elements I want to close all the lists)
Thanks in advance
JavaScript
x
10
10
1
const lists = document.querySelectorAll(".list");
2
3
function closeList() {
4
document.addEventListener("click", () => {
5
if(lists.some((list) => list.style.display != "none")) {
6
return lists.style.display = none;
7
} else return;
8
});
9
};
10
Advertisement
Answer
You can use Node.contains() to check if Event.target is a descendant of element and run callback if not:
JavaScript
1
10
10
1
function onClickOutside(ele, cb) {
2
document.addEventListener('click', event => {
3
if (!ele.contains(event.target)) cb();
4
});
5
};
6
7
// Using
8
onClickOutside('#list', () => console.log('Hi!'));
9
// Will log 'Hi!' whenever the user clicks outside of #list
10