1

In the JS code, there is a part which prints some number of items, and next to each item there is an icon for removing the item next to it:

 <img src="images/remove.png"  class="remove" onClick="remove_item(${index})"> 

So, when the user clicked a bin the item next to it will be removed by the function below. The point is that items are need to be stored in an array called list. So item will be removed from list. The function render is for printing the items again.

function remove_item(index) {
  list.splice(index, 1);
  localStorage.setItem('list', JSON.stringify(list));
  render(list); 

The code which is up is working perfectly. However the issue is that the task is needed to be done by using eventListener. For that img part is edited like below.

<img src="images/remove.png"  class="remove" data-index="${index}">

And the part which will remove the item from list is like below.

let remove = document.querySelectorAll(".remove"); 
Array.from(remove).forEach((el) => {
el.addEventListener('click', function() { 
    let index = el.getAttribute('data-index');
    list.splice(index, 1);
    render(list);
    localStorage.setItem('list', JSON.stringify(list));
})});

The problem is that, code is working only when page is refreshed before each click to any icon. So after clicking the icon, I have to refresh and then click again for removing some other item. How I can fix that?

isherwood
  • 58,414
  • 16
  • 114
  • 157
Caeculus
  • 89
  • 8
  • 1
    You're removing eventListeners when `render(list)`. You actually need to remove the list item, not redraw the whole list. – Kosh Oct 01 '21 at 19:46

1 Answers1

0

When you re-render the list the elements are all replaced, which strips the event handlers. You should probably just remove the actual element:

el.addEventListener('click', function() { 
    let index = el.getAttribute('data-index');
    list.splice(index, 1);
    el.remove();
    localStorage.setItem('list', JSON.stringify(list));
})});

Either that or run the code again after render which attaches the event handlers. Whatever makes the most sense with how you're rendering.

isherwood
  • 58,414
  • 16
  • 114
  • 157
  • After you remove the element from the list, the list indexes no longer correspond to `data-index`. – Barmar Oct 01 '21 at 19:52