-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcart.js
More file actions
70 lines (60 loc) · 2.25 KB
/
cart.js
File metadata and controls
70 lines (60 loc) · 2.25 KB
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
// Fetch cart items from localStorage
let cartItems = JSON.parse(localStorage.getItem('cart')) || [];
// Function to display the cart
function displayCart() {
const cartTable = document.getElementById('cart-items');
cartTable.innerHTML = '';
cartItems.forEach(item => {
const row = `
<tr>
<td>${item.name}</td>
<td>${item.quantity}</td>
<td>
<button class="btn btn-danger" onclick="removeFromCart('${item.name}')">Remove</button>
</td>
</tr>
`;
cartTable.innerHTML += row;
});
// Update cart in localStorage
localStorage.setItem('cart', JSON.stringify(cartItems));
}
// Function to remove an item from the cart
function removeFromCart(productName) {
const itemIndex = cartItems.findIndex(item => item.name === productName);
if (itemIndex > -1) {
if (cartItems[itemIndex].quantity > 1) {
// Reduce quantity by 1
cartItems[itemIndex].quantity -= 1;
showNotification(`One ${productName} removed from cart. Remaining: ${cartItems[itemIndex].quantity}`);
} else {
// Remove the item completely if quantity is 1
cartItems.splice(itemIndex, 1);
showNotification(`${productName} has been removed from your cart!`);
}
displayCart();
}
}
function continueShopping() {
showNotification("Take a look at more products!");
// Redirect to homepage after 2 seconds
setTimeout(() => {
window.location.href = "index.html"; // Adjust the URL if your homepage is in a different location
}, 2000); // Delay of 2 seconds before redirect
}
// Custom Notification Function
function showNotification(message) {
const notification = document.getElementById('notification');
notification.innerText = message;
notification.classList.remove('hidden');
notification.classList.add('show');
// Hide notification after 3 seconds
setTimeout(() => {
notification.classList.remove('show');
setTimeout(() => {
notification.classList.add('hidden');
}, 300); // Wait for transition to complete
}, 3000); // Notification duration
}
// Display initial cart items
displayCart();