-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();
    }
}));
5
  • 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. Commented Jul 22, 2021 at 14:24
  • event delegation..... learn about it. Commented Jul 22, 2021 at 14:25
  • 1
    Duplicate Event binding on dynamically created elements? Commented Jul 22, 2021 at 14:26
  • Non-jQuery answer here: stackoverflow.com/a/27373951/5734311 Commented Jul 22, 2021 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. Commented Jul 22, 2021 at 14:29

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Here's the existing answer that offers a better way to do this. Please check for duplicates before posting answers.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.