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?