0

I am building a simple todos project, where the user can input and add items to a list as well as delete any item. For deleting the item, the user can click on a delete icon and then can confirm the deletion via a popup. Now, I've attached an eventListener to the list of items, and it checks if the user clicks on the delete button for any specific list item. If it does, a popup appears. Now I want to listen for a click event on the 'confirm' button in the popup. I have tried to do this first by attaching an eventListener to the button like this:

entryList.addEventListener('click', e=> {
    let node = e.target.parentNode;
    if(e.target.classList.contains('delete')){
        popup.style.display = 'block';
        button.addEventListener('click', ()=> {
            popup.style.display = 'none';
            node.remove()
     })
    }
    
})

This gives a response where if I don't confirm a deletion but then delete a different item in the list, all of the items that I previously hadn't confirmed for deletion get deleted. Like for eg., if I had clicked the delete button on item 5 and then cleared the popup and then clicked the delete button for item 4 and confirm it, both items 4 and 5 get deleted from the list.

In the same problem if I instead use the onclick property for the button like this:

entryList.addEventListener('click', e=> {
    let node = e.target.parentNode;
    if(e.target.classList.contains('delete')){
        popup.style.display = 'block';
        button.onclick = ()=>{
            popup.style.display = 'none';
            node.remove()
        }
    }
})

I am getting the desired output.

Why are both the code piece showing different outputs and what are the exact differences between the onclick property and click eventListener?

inrittik
  • 3
  • 1
  • It's possible to add *multiple* event handlers with `addEventlistener`, whereas the `onclick` *property* can of course only reference a single event handler. In the first example, every time `entryList` is clicked a new event handler is added to `button`. – Felix Kling Nov 25 '21 at 09:21

1 Answers1

0

The difference in that code is that when you use addEventListener, you're adding an event handler, which doesn't do anything to any other event handlers that have already been added. So in your item 5 and item 4 example, when the button is clicked, both handlers get called.

In contrast, when you assign to onclick, you're replacing any previous handler that was on the onclick property with a new one (just like any other assignment), so the previous one isn't there anymore.

With fuller context we could probably show you how to avoid dynamically attaching handlers at all, but the minimal change if you use addEventListener is to remember the function and call removeEventListener when you no longer want that handler called.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875