Skip to content
Advertisement

addEventListener stops after the first execution

I’m running into an issue with my current JS project. It’s a simple library where the user inputs the info and spits it out onto the page. I have a delete button that I add to each new div, which I’ve added event listeners to the buttons. When I click delete, it will delete the first one – but that’s it. It stops working if i want to delete more than one book.

I think my problem is how I’m targeting the data-set/index values that i assign each div, but I’m not sure. I’ve tried for loops, for each, etc and can’t seem to figure it out.

Any help would be appreciated.

JavaScript
JavaScript

Advertisement

Answer

When you are building an app like this it’s often best to remove the parts that aren’t relevant such as the form and all it;s associated functions in order to work on specific parts of it like these user interactions.

Here’s a scaled down version with a completely different approach that adds event listeners to the book elements individually as you create them.

Then instead of worrying about indexing, use array methods to find the book object in the library. So rather than rebuild all the elements when you remove one you simply remove both the element and the object in the array.

It’s broken down into smaller functions like addBookEvents() then within each different event handler uses either Array.prototype.find() or Array.prototype.findIndex() to modify library.

Your approach of rebuilding all the elements just to change the indexing is not very scalable or efficient. In order to create the library array used here I just used your library.push(book1,book2...) and then ran console.log(JSON.stringify(library)) and pasted it into this code to keep it lean for this stage.

Note that I changed data-index to data-title on the elements with assumption that titles will be unique in the array. That then allows searching array to find the specific book object. Using a unique book id is more reliable in case of title duplications

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement