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 isn't a function so i may not have understand 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
const lists = document.querySelectorAll(".list");
function closeList() {
document.addEventListener("click", () => {
if(lists.some((list) => list.style.display != "none")) {
return lists.style.display = none;
} else return;
});
};
CodePudding user response:
You can use Node.contains() to check if Event.target is a descendant of element and run callback if not:
function onClickOutside(ele, cb) {
document.addEventListener('click', event => {
if (!ele.contains(event.target)) cb();
});
};
// Using
onClickOutside('#list', () => console.log('Hi!'));
// Will log 'Hi!' whenever the user clicks outside of #list
CodePudding user response:
I suggest for you this method :
@HostListener('document:click', ['$event.target'])
public onClick(targetElement) {
const event = this.elementRef.nativeElement.contains(targetElement);
if (targetElement && !event) {
if (this.isClickedOutside) {
// this.shownInfo = false;
}
}
or you can also just a javascript :
window.addEventListener('click', function(e){
if (document.getElementById('clickbox').contains(e.target)){
// Clicked in box
} else{
// Clicked outside the box
}
});
CodePudding user response:
Js querySelectorAll() will return a nodeList, but nodeList doesn't have method some(). You can use forEach() the following:
const lists = document.querySelectorAll(".list");
function closeList() {
document.addEventListener("click", () => {
lists.forEach(list => {
if(list.style.display != "none") lists.style.display = none
})
});
};