I wrote up a code that displays food items on the screen by creating elements of varied tags dynamically. And I've placed the entire process in one function called displayMenuItems. Now the first set of dynamically created buttons (i.e 'add-btn' buttons), when I add an event to them, the event will fire without a hitch when clicked. However the second set of dynamically created buttons (i.e 'delete-btn' buttons), when an event is added to them, the event will not fire when clicked. I've no idea why this complication arises when the code of the second set of buttons is similar to the first set of buttons. Could you fix this problem, I would really appreciate it?
const menu = [
{
id: 1,
title: "GUNPOWDER GOBHI",
category: "Small Plates",
price: 16.99,
img: "sp1.png",
desc: `Crispy Cauliflower, Spicy Lentil Dust`,
},
{
id: 2,
title: "SHRIMP KOLIWADA",
category: "Small Plates",
price: 13.99,
img: "sp2.jpg",
desc: `Crispy Popcorn Style Fritters, Pickled Mango Sauce`,
},
{
id: 3,
title: "GHEE ROAST CHICKEN WINGS",
category: "Small Plates",
price: 6.99,
img: "sp3.jpg",
desc: `Kundapur Chicken Masala`,
},
]
const sectionCenter = document.querySelector(".section-center");
const listContainer = document.querySelector('.list-container');
window.addEventListener("DOMContentLoaded", function () {
diplayMenuItems(menu);
});
function diplayMenuItems(menuItems) {
let displayMenu = menuItems.map(function (item) {
return `<article class="menu-item">
<img src=${item.img} alt=${item.title} class="photo" />
<div class="item-info">
<h4>${item.title}</h4>
<h4 class="price">$${item.price}</h4>
<p class="item-text">
${item.desc}
</p>
<button class="add-btn" data-title="${item.title}" data-price="$${item.price}">Add To List</button>
</div>
</article>`;
});
displayMenu = displayMenu.join("");
sectionCenter.innerHTML = displayMenu;
const addBtns = document.querySelectorAll('.add-btn');
addBtns.forEach(function(btn){
btn.addEventListener('click', function(e){
const title = e.currentTarget.dataset.title;
const price = e.currentTarget.dataset.price;
const para = document.createElement('div');
para.classList.add('item-list');
para.innerHTML = `<p class="item">${title}</p>
<p class="item">${price}</p>
<button class="delete-btn" data-title="${title}">x</button>`
listContainer.appendChild(para);
});
});
const deleteBtns = document.querySelectorAll('.delete-btn');
deleteBtns.forEach(function(btn){
btn.addEventListener('click', function(e){
const title = e.currentTarget.dataset.title;
console.log(title);
});
});
}