when i click on the add to cart button the single product page shows up.what can i do to seperate the add to cart button from the product page link when i click on add to cart button the product should be added to cart and the product page should not be displayed.
My Product Render Code
const renderProducts = () => {
products.forEach((product) => {
let newProduct = document.createElement("a");
newProduct.href = `product.html?id=${product.id}`;
newProduct.classList.add("product");
let inCart = cart.find((x) => x.id === product.id);
let disabled = inCart ? "disabled" : "";
let text = inCart ? "In Cart" : "Add To Cart";
newProduct.innerHTML = `
<div class="product">
<img
src="${product.image}"
alt=""
/>
<h3>${product.title}</h3>
<p>${product.category}</p>
<h5>$${product.price}</h5>
<button ${disabled} data-id="${product.id}">${text}</button>
</div>
`;
selectors.products.appendChild(newProduct);
});
};
My add to cart Code
const renderCart = () => {
let cartQty = cart.reduce((sum, item) => {
return sum + item.qty;
}, 0);
selectors.cartQty.innerHTML = cartQty;
selectors.cartQty.classList.toggle("visible", cartQty);
selectors.cartTotal.textContent = calculateTotal();
if (cart.length === 0) {
selectors.cartBody.innerHTML =
'<div class="empty-cart">Your Cart is Empty</div>';
return;
}
selectors.cartBody.innerHTML = cart.map(({ id, qty }) => {
let product = products.find((x) => x.id === id);
let { image, title, price } = product;
let amount = price * qty;
return `
<div class="cart-item" data-id="${id}">
<img src="${image}" alt="" />
<div class="cart-item-detail">
<h3>${title}</h3>
<h5>$${price}</h5>
<div class="cart-item-amount">
<i class="bi bi-dash-lg" data-btn="decr"></i>
<span class="qty">${qty}</span>
<i class="bi bi-plus-lg" data-btn="incr"></i>
<span class="cart-item-price">${amount}</span>
</div>
</div>
</div>
`;
});
};
My Single Product Page Link Code
let products = [];
fetch("https://fakestoreapi.com/products")
.then((res) => res.json())
.then((data) => {
products = data;
showProducts();
});
function showProducts() {
let productId = new URLSearchParams(window.location.search).get("id");
let thisProduct = products.filter((value) => {
return value.id == productId;
})[0];
if (!productId) {
window.location.href = "index.html";
}
document.querySelector(".singleImage").src = thisProduct.image;
document.querySelector(".singleName").textContent = thisProduct.title;
document.querySelector(".dingleDet").textContent = thisProduct.description;
document.querySelector(".singlePrice").textContent = thisProduct.price;
document.querySelector(".singleCat").textContent = thisProduct.category;
}
please help me to solve the problem my product page is showing oki with details but clicking the cart button navigates me to single product page.