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 make event listener to keep working after elements are added to the DOM (pure js)

Hi,

I have this listener:

//close all detail tags when click happens outside
document.addEventListener('click', function(e) {
 if (!details.some(f => f.contains(e.target))) {
   details.forEach(f => f.removeAttribute('open'));
 } else {
   details.forEach(f => !f.contains(e.target) ? f.removeAttribute('open') : '');
 }
})

it automatically closes all the open details tags when a new one is clicked or you click anywhere on the page, that works fine. Problems arise when a new detail tag will be added dynamically then the listener wont work for them. I was reading other questions related and most suggested delegation but this doesnt seem to be the case because the listener should work for both normal tags and dynamic tags as well.

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

I tried some suggestions like this:

document.addEventListener('click', function(e){
    if(e.target && e.target.id== 'myDynamicallyAddedElementID'){
         //my code
    }
});

but no change. You can test it here https://jsfiddle.net/nxv03wjo/ and here https://jsfiddle.net/nxv03wjo/1/

Whats the trick here?

Thank you.

>Solution :

Just retrieve the details elements inside the click listener?

document.addEventListener('click', function (e) {
    const details = [...document.querySelectorAll('details')];
    if (!details.some(f => f.contains(e.target))) {
        details.forEach(f => f.removeAttribute('open'));
    } else {
        details.forEach(f => !f.contains(e.target) ? f.removeAttribute('open') : '');
    }
});
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