Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to close an element by clicking outside of it?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
    });
};

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading