-1

I have the following piece of Javascript code that works when the DOM is loaded. But when I add new buttons dynamically (after dropzone upload), those new buttons don't respond. What should I add to this script?

document.querySelectorAll('.to-delete').forEach((el) => el.addEventListener('click', function(e) {
    e.preventDefault();
    if (confirm("Press a button!")) {
        fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                'id': el.getAttribute('data-delete-attachment'),
            })

        }).then(response => {
            if (response.ok) {
                el.closest('.columns').remove();
            }
        }).catch(err => {
            console.error(err);
        });
        //console.log();
    }
}));
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Salines
  • 5,674
  • 3
  • 25
  • 50
  • You should add listeners to those buttons you're creating dynamically, i.e., as you create the buttons and add them to the DOM you need to attach onclick listeners to them with the same handler. – Ameer Jul 22 '21 at 14:24
  • event delegation..... learn about it. – epascarello Jul 22 '21 at 14:25
  • 1
    Duplicate [Event binding on dynamically created elements?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) –  Jul 22 '21 at 14:26
  • Non-jQuery answer here: https://stackoverflow.com/a/27373951/5734311 –  Jul 22 '21 at 14:27
  • 1
    @Kinglish That's not a duplicate of this question. Yours is about var and assigning event handlers in a loop (and the well known pitfall of that), and the current answer to that is to use `let` instead anyway. –  Jul 22 '21 at 14:29

1 Answers1

2

You basically need to attach the event listener to the new elements whenever you create them and add them to the DOM.

If you somehow can't modify the code that creates those elements, you could make an interval that checks for new elements every second or so, but this is of course more of a hack.

Kelvin Schoofs
  • 8,323
  • 1
  • 12
  • 31
  • [Here's](https://stackoverflow.com/a/27373951/5734311) the existing answer that offers a better way to do this. Please check for duplicates before posting answers. –  Jul 22 '21 at 14:28