I have a HTLM, CSS and JavaScript files, I’m try to create a product browser there three categories of products(Electonics, Clothing, Books) and I want to create a Wishlist where the user can add the products in whisklist.
I’m facing the problem when I run the HTML file I’m not showing the products but then I click the button on anyone from the category then I’m showing that category product but I want to show initial three products when I run the HTML file but I’m facing the problems at that stage.
HTML code
<body>
<h1>Product Browser </h1>
<div id="categories">
<button onclick="filterProducts('electronics')">Electronics</button>
<button onclick="filterProducts('clothing')">Clothing</button>
<button onclick="filterProducts('books')">Books</button>
</div>
<div id="product-list">
</div>
<div id="wishlist">
<h2>Wishlist</h2>
<div id="wishlist-items"></div>
<p id="wishlist-summary"></p>
<button onclick="clearWishlist()">Clear Wishlist</button>
</div>
<script src="LabExamScript.js"></script>
JAVASCRIPT code
const products = [
{ id: 1, name: "Smartphone", category: "electronics", image: "https://via.placeholder.com/150" },
{ id: 2, name: "Jeans", category: "clothing", image: "https://via.placeholder.com/150" },
{ id: 3, name: "Magazine", category: "books", image: "https://via.placeholder.com/150" }
];
let whishlist = []
function filterProducts(category) {
const productList = document.getElementById("product-list");
productList.innerHTML = ""; // Clear previous content
// Filter products by category and display them
const filteredProducts = products.filter(product => product.category === category);
filteredProducts.forEach(product => {
const productCard = document.createElement("div");
productCard.classList.add("product-card");
productCard.innerHTML = `
<img src="${product.image}" alt="${product.name}">
<h2>${product.name}</h2>
<button onclick="addToWishlist(${product.id})">Add to Wishlist</button>
`;
productList.appendChild(productCard);
});
}
Outputs
Initial Output
when I clicked any product button
2
Answers
The issue is most probably that your
filterProducts
function is only called when you click a category button. To display initial products, you need to call it once when the page loads.Change your filter to support search for all kinds of products:
And call it on page load:
Or if you prefer, you can pass a specific category as the default choice on page load.