<!-- language: lang-js -->
(function()
{
//add item to the cart
const cartBtn = document.querySelectorAll('.bi-
shopping-bag4');
cartBtn.forEach(function(btn)
{
btn.addEventListener("click", function(event)
{
//code goes here...
})
})
//remove item from the cart
const deleteBtn= document.querySelectorAll('.zmdi-delete');
cartBtn.forEach(function(btn)
{
btn.addEventListener("click", function(event)
{
//code goes here...
})
})
})();
add item to the cart: dynamically appends created 'div' element as a child inside its parent div.
remove item from the cart: removes those dynamically appended items from the cart with element.remove() function.
The delete button doesn't alert click event. I know that I must implement something that binds remove event with the dynamically appended elements but the solutions in the binding event on dynamically created elements don't solve my problem or its likely that I could't properly implement it in my project pattern. What I have done so far:
1) I tried to add jquery fn.on
on the eventListeners, I simply changed the js syntax btn.addEventListener("click", function(event)
with jquery's $(btn).on("click", function(event)
2) I tried to implement pure js solution :
function hasClass(elem, className) {
return elem.classList.contains(className);
}
const cartBtn = document.querySelectorAll('.bi-shopping-bag4');
cartBtn.forEach(function(btn)
{
btn.addEventListener('click', function (e)
{
if (hasClass(event.target, 'bi-shopping-bag4')) {
// ..bi-shopping-bag4clicked
// Do your thing
}, false);
})
const deleteBtn= document.querySelectorAll('.zmdi-delete');
deleteBtn.forEach(function(btn)
{
btn.addEventListener('click', function (event)
{
if (hasClass(event.target, 'zmdi-delete')) {
// ..bi-shopping-bag4clicked
// Do your thing
}, false);
})
but to no avail..So what have I done wrong?