I am still in the process of writing this, but I am now in a slump. This might be a novice question but is there a way to click on the image itself? I was hoping to incorprate it as an e-commerce website [add to cart] feature. However, the alert only appears when I click outside the image, and not on the image itself. Any advices and suggestions will be very much appreciated!
let listProductHTML = document.querySelector('.ProductContainer');
let listProduct = [];
const addProductToHTML = () => {
listProductHTML.innerHTML = '';
if(listProduct.length > 0){
listProduct.forEach(Product => {
let newProduct = document.createElement('div');
newProduct.classList.add('iconProduct');
newProduct.dataset.id = Product.id;
newProduct.innerHTML = `
<img alt="Product image"
src="${Product.image}" width="128" height="128">
<p>${Product.name}</p>
`;
listProductHTML.appendChild(newProduct);
})
}
}
listProductHTML.addEventListener('click', (event) => {
let positionClick = event.target;
let Product_id = positionClick.dataset.id;
if(positionClick.classList.contains('iconProduct')){
let Product_id = positionClick.dataset.id;
alert(Product_id);
}
//I am unable to move forward at this point
})
const initApp = () => {
//get data from json
fetch('Products.json')
.then(response => response.json())
.then(data => {
listProduct = data;
addProductToHTML();
})
}
initApp();