-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
70 lines (60 loc) · 1.93 KB
/
main.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
import './src/styles/index.css';
import { products } from './src/data/products.js';
import { Cart } from './src/js/cart.js';
import { setupSearch } from './src/js/search.js';
// Initialize cart
const cart = new Cart();
// Setup cart button functionality
const cartButton = document.getElementById('cart-button');
const cartContainer = document.getElementById('cart-container');
cartButton.addEventListener('click', () => {
cartContainer.classList.toggle('active');
});
// Close cart when clicking outside
document.addEventListener('click', (e) => {
if (!cartContainer.contains(e.target) && !cartButton.contains(e.target)) {
cartContainer.classList.remove('active');
}
});
// Function to format price
function formatPrice(price) {
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD'
}).format(price);
}
// Function to display products
function displayProducts(productsToShow) {
const productsGrid = document.getElementById('products-grid');
productsGrid.innerHTML = productsToShow.map(product => `
<div class="product-card">
<img src="${product.image}" alt="${product.title}" class="product-image">
<div class="product-info">
<h3>${product.title}</h3>
<p class="description">${product.description}</p>
<p class="price">${formatPrice(product.price)}</p>
<button
class="button"
onclick="window.addToCart(${product.id})"
>
Add to Cart
</button>
</div>
</div>
`).join('');
}
// Initialize search functionality
setupSearch(products, displayProducts);
// Make addToCart function available globally
window.addToCart = (productId) => {
const product = products.find(p => p.id === productId);
if (product) {
cart.addItem(product);
}
};
// Make removeFromCart function available globally
window.removeFromCart = (productId) => {
cart.removeItem(productId);
};
// Initial product display
displayProducts(products);