Neha Chaudhary
Neha Chaudhary

Reputation: 1279

How do I add event delegation here?

I'm making a pizza ordering application using pure javascript. In the CART section, I have two click operations - increase /decrease the item quantity and remove the item from cart. I have two event listeners for these two operations. I want to make use of event delegation here. The DOM structure looks like this. Here the class cart-items is the parent class of all the items that are dynamically added into the card. Every item present in the cart gets a div and the ID associated with the pizza item chosen is assigned as ID for that item. For example, I add the pizza item with ID 4 in my cart, so a <div> with id 4 is added in the DOM. :- DOM Structure

Here are the event listeners for the increase/decrease in quantity and remove item from cart.

//event listener attached when remove button is clicked on
  let removeCartItemButtons = document.getElementsByClassName("btn-danger");
  for (let i = 0; i < removeCartItemButtons.length; i++) {
    let button = removeCartItemButtons[i];
    button.addEventListener("click", removeCartItem);
  }

  //event listener attatched when quantity is increased or decreased
  let quantityInputs = document.getElementsByClassName("cart-quantity-input");
  for (let i = 0; i < quantityInputs.length; i++) {
    let input = quantityInputs[i];
    input.addEventListener("change", quantityChanged);
  }

MY TAKE ON:

document
    .getElementsByClassName("cart-items")
    .addEventListener()
    );

I want to make use of event delegation and don't want to create multiple event listeners. So, I'm fetching the cart-items which is basically the parent element here for the CART section. Now, how do I add the two event listeners inside the above code.
Please help!

Upvotes: 1

Views: 151

Answers (1)

Unmitigated
Unmitigated

Reputation: 89497

for(const el of document.querySelectorAll(".cart-items")){
    el.addEventListener('click', function(e){
        if(e.target.matches('.btn-danger')){
            removeCartItem(e.target);
        }
    });
    el.addEventListener('change', function(e){
        if(e.target.matches('.cart-quantity-input')){
            quantityChanged(e.target);
        }
    });
}

Upvotes: 1

Related Questions