-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
168 lines (143 loc) · 6.36 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
// Fetch products and render them on the page
fetch("https://fakestoreapi.com/products/")
.then((res) => res.json())
.then((data) => {
renderProducts(data); // Render fetched products
updateCartCount(); // Update cart count after products are rendered
});
// Function to render products
const renderProducts = (products) => {
const productGrid = document.querySelector('.product-grid');
productGrid.innerHTML = ''; // Clear existing products
products.forEach((product) => {
const productCard = document.createElement('a');
productCard.href = `product.html?id=${product.id}`; // Link to product detail page
productCard.className = 'product-card';
productCard.setAttribute('data-category', product.category); // Set data-category for filtering
// Truncate the title if it's longer than 16 characters
const truncatedTitle = product.title.length > 16
? product.title.slice(0, 16) + '...'
: product.title;
// Construct product card HTML
productCard.innerHTML = `
<img src="${product.image}" alt="${product.title}" class="product-image">
<div class="product-details">
<h3>${truncatedTitle}</h3>
<p>$${product.price.toFixed(2)}</p>
<button onclick="addToCart(${product.id})">Add to Cart</button>
</div>
`;
productGrid.appendChild(productCard); // Append product card to the grid
});
};
// Function to update cart count
const updateCartCount = () => {
const cart = JSON.parse(localStorage.getItem("cart")) || []; // Retrieve cart from local storage
const cartCount = document.getElementById("cart-count");
cartCount.innerText = cart.length; // Update count display
cartCount.style.display = cart.length > 0 ? "block" : "none"; // Show or hide based on count
};
// Function to add to cart and update count
function addToCart(productId) {
fetch(`https://fakestoreapi.com/products/${productId}`)
.then(res => res.json())
.then(product => {
const cart = JSON.parse(localStorage.getItem("cart")) || []; // Retrieve existing cart
cart.push(product); // Add new product to cart
localStorage.setItem("cart", JSON.stringify(cart)); // Update local storage
updateCartCount(); // Update cart count immediately
});
}
// Theme Toggle Functionality
const themeToggle = document.getElementById("theme-toggle");
// Function to set theme from local storage
const setTheme = () => {
const theme = localStorage.getItem("theme") || "light"; // Default to light theme
document.body.classList.toggle("dark", theme === "dark"); // Apply dark theme if set
themeToggle.innerHTML = theme === "dark"
? '<i class="fas fa-sun"></i>' // Sun icon for light mode
: '<i class="fas fa-moon"></i>'; // Moon icon for dark mode
};
// Call setTheme on page load
setTheme();
// Add click event for theme toggle
themeToggle.addEventListener("click", () => {
document.body.classList.toggle("dark"); // Toggle dark class on body
const newTheme = document.body.classList.contains("dark") ? "dark" : "light"; // Determine new theme
localStorage.setItem("theme", newTheme); // Save new theme to local storage
themeToggle.innerHTML = newTheme === "dark"
? '<i class="fas fa-sun"></i>' // Update icon
: '<i class="fas fa-moon"></i>';
});
// Product Filtering Functionality
const categoryFilter = document.getElementById("category-filter");
categoryFilter?.addEventListener("change", function () {
const selectedCategory = this.value; // Get selected category
const products = document.querySelectorAll(".product-card");
products.forEach((product) => {
const category = product.dataset.category; // Get category from data attribute
product.style.display =
selectedCategory === "" || category === selectedCategory
? "block" // Show product if it matches the filter
: "none"; // Hide otherwise
});
});
// Hamburger Menu Functionality
const hamburger = document.getElementById("hamburger");
const closeHamburger = document.getElementById("close-hamburger");
const navLinks = document.getElementById("nav-links");
// Function to check window size and adjust icon visibility
const checkWindowSize = () => {
if (window.innerWidth > 480) {
hamburger.style.display = "none"; // Hide hamburger icon
closeHamburger.style.display = "none"; // Hide close icon
navLinks.classList.remove("active"); // Hide nav links if active
} else {
hamburger.style.display = "block"; // Show hamburger if under 480px
}
};
// Initial check on page load
checkWindowSize();
// Event listener for window resize
window.addEventListener('resize', checkWindowSize);
// Add click event for hamburger icon
hamburger.addEventListener("click", () => {
navLinks.classList.add("active"); // Show nav links
closeHamburger.style.display = "block"; // Show close icon
hamburger.style.display = "none"; // Hide hamburger icon
});
// Add click event for close icon
closeHamburger.addEventListener("click", () => {
navLinks.classList.remove("active"); // Hide nav links
closeHamburger.style.display = "none"; // Hide close icon
hamburger.style.display = "block"; // Show hamburger icon
});
// Render Cart Items
const renderCartItems = () => {
const cart = JSON.parse(localStorage.getItem("cart")) || []; // Retrieve cart items
const cartContainer = document.querySelector('.cart-container'); // Ensure this element exists in your HTML
cartContainer.innerHTML = ''; // Clear existing items
cart.forEach(item => {
const cartItem = document.createElement('div');
cartItem.className = 'cart-item';
cartItem.innerHTML = `
<img src="${item.image}" alt="${item.title}" class="cart-item-image">
<div class="cart-item-details">
<h3>${item.title}</h3>
<p>$${item.price.toFixed(2)}</p>
</div>
`;
cartContainer.appendChild(cartItem); // Append item to cart
});
// Optionally add a message if the cart is empty
if (cart.length === 0) {
cartContainer.innerHTML = '<p>Your cart is empty!</p>'; // Message for empty cart
}
};
// Add an event listener to the cart icon
const cartIcon = document.getElementById("cart-icon"); // Ensure you have an element with this ID
cartIcon.addEventListener("click", renderCartItems); // Render cart items on click
// Call this function on page load
window.onload = () => {
updateCartCount(); // Update cart count on load
};