#Button works, but then I add items to cart and button stops working

1 messages · Page 1 of 1 (latest)

tall bolt
brisk ether
#

That's because when you FIRST go into the page you do this:

render()

const buyBtn = document.getElementById('purchase-btn')
// snipped for clarity
buyBtn.addEventListener("click", function(e){...

render() calls getCompleteOrderHtml() which creates a new purchase button. Then you get the button out of the page and add the event listener. All good so far.

Later when you add an item you again call render() which again calls getCompleteOrderHtml() which creates a NEW purchase button. This new button has NO click handler on it... The original one has been replaced by this new one - that's what happens when you use the .innerHTML function. It replaces all previous content with the new content.

So, there are a few ways to fix this issue including adding the event listener inside the render() method OR (better) reworking the way that the getCompleteOrderHtml works - this is static content and doesn't need to be recreated every time...

tall bolt
#

Ah, thank you! So reprinting code an event is attached removes the event from it and needs to be added again, that's good to know. I removed the getCompleteOrderHtml function and just popped the button into the html file and it now works. 🙂