I am on module 5 solo project, the restaraunt app. The 'Complete order' button works before I add any items to the cart, but after I add items the button stops working. Here's the netlify of the app https://restaraunt-app.netlify.app/
and the github https://github.com/nialldev/restaraunt-app can anyone provide any idea as to what's going on?
#Button works, but then I add items to cart and button stops working
1 messages · Page 1 of 1 (latest)
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...
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. 🙂