-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
276 lines (256 loc) · 11.5 KB
/
script.js
File metadata and controls
276 lines (256 loc) · 11.5 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
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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
// Корзина хранится в localStorage
const CART_KEY = 'cart';
function getCart() {
return JSON.parse(localStorage.getItem(CART_KEY) || '[]');
}
function saveCart(cart) {
localStorage.setItem(CART_KEY, JSON.stringify(cart));
}
function addToCart(product) {
const cart = getCart();
const existing = cart.find(item => item.id === product.id);
if (existing) {
existing.count += 1;
} else {
cart.push({...product, count: 1});
}
saveCart(cart);
updateCartUI();
}
function removeFromCart(productId) {
let cart = getCart();
cart = cart.filter(item => item.id !== productId);
saveCart(cart);
updateCartUI();
}
// --- UI Elements ---
function getCartCount() {
let cart = JSON.parse(localStorage.getItem('cart') || '[]');
return cart.reduce((sum, item) => sum + (item.qty || 1), 0);
}
function getCartTotal() {
let cart = JSON.parse(localStorage.getItem('cart') || '[]');
return cart.reduce((sum, item) => sum + (item.price * (item.qty || 1)), 0);
}
function showCartNotification(product) {
let notif = document.createElement('div');
notif.className = 'cart-notification';
notif.innerHTML = `Товар <b>${product.name}</b> добавлен в корзину!`;
document.body.appendChild(notif);
setTimeout(() => notif.remove(), 1800);
}
function updateCartUI() {
// Счётчик в иконке корзины (добавьте элемент с id="cart-count" в разметку, если нужно)
let count = getCartCount();
let el = document.getElementById('cart-count');
if (el) el.textContent = count > 0 ? count : '';
// Итоговая сумма (например, в корзине)
let totalEl = document.getElementById('total-amount');
if (totalEl) totalEl.textContent = getCartTotal().toLocaleString();
renderMiniCart();
}
// Модальное окно корзины
function openCartModal() {
const modal = document.querySelector('.modal-cart');
if (modal) modal.classList.add('open');
}
function closeCartModal() {
const modal = document.querySelector('.modal-cart');
if (modal) modal.classList.remove('open');
}
// --- Обработка кликов ---
document.addEventListener('DOMContentLoaded', function () {
// Универсальный обработчик для всех страниц
function handleAddToCart(e) {
let target = e.target;
// Проверяем, кликнули ли по SVG внутри иконки
if (target.tagName === 'svg' || target.tagName === 'path') {
target = target.closest('[data-id][data-name][data-price]');
}
// Проверяем, есть ли нужные data-атрибуты
if (target && target.hasAttribute('data-id') && target.hasAttribute('data-name') && target.hasAttribute('data-price')) {
const id = target.getAttribute('data-id');
const name = target.getAttribute('data-name');
const price = parseInt(target.getAttribute('data-price'), 10);
addToCart({ id, name, price });
// Можно добавить анимацию или уведомление
e.preventDefault();
e.stopPropagation();
}
}
// Навешиваем обработчик на контейнер каталога и спецпредложений (делегирование)
document.body.addEventListener('click', function (e) {
if (
e.target.closest('.catalog__img-container[data-id]') ||
e.target.closest('.catalog__link-icon--basket[data-id]') ||
e.target.closest('.offer__link-icon--basket[data-id]') ||
e.target.closest('.offer__img-container[data-id]')
) {
let target = e.target.closest('[data-id][data-name][data-price]');
if (target) {
const id = target.getAttribute('data-id');
const name = target.getAttribute('data-name');
const price = parseInt(target.getAttribute('data-price'), 10);
addToCart({ id, name, price });
showCartNotification({ id, name, price });
e.preventDefault();
e.stopPropagation();
}
}
});
// Функция добавления товара в корзину (пример)
function addToCart(product) {
// Получаем корзину из localStorage
let cart = JSON.parse(localStorage.getItem('cart') || '[]');
// Проверяем, есть ли уже такой товар
const existing = cart.find(item => item.id === product.id);
if (existing) {
existing.qty = (existing.qty || 1) + 1;
} else {
cart.push({ ...product, qty: 1 });
}
localStorage.setItem('cart', JSON.stringify(cart));
updateCartUI();
}
// Функция обновления UI корзины (заглушка)
function updateCartUI() {
// Здесь можно обновить счетчик, сумму и т.д.
// Например, обновить число товаров в иконке корзины
// или перерисовать содержимое модального окна/страницы корзины
}
// --- Стили для уведомления ---
(function(){
const style = document.createElement('style');
style.innerHTML = `.cart-notification {position:fixed;top:30px;right:30px;z-index:9999;background:#3fa9f5;color:#fff;padding:16px 28px;border-radius:12px;font-size:1.1rem;box-shadow:0 2px 12px rgba(0,0,0,0.12);animation:cartNotifIn 0.2s;}
@keyframes cartNotifIn {from{opacity:0;transform:translateY(-20px);}to{opacity:1;transform:translateY(0);}}`;
document.head.appendChild(style);
})();
renderMiniCart();
});
function cartItemTemplate(item, context = 'main') {
// context: 'main' (корзина), 'mini' (мини-корзина)
const isMini = context === 'mini';
const isMobile = window.innerWidth <= 600; // для мобильной версии
const imgSize = isMini ? 144 : 137;
return `
<div class="cart__item${isMini ? ' cart__item--mini' : ''}" data-id="${item.id}">
<div class="cart__left">
${!isMini && isMobile ? '' : `<img src="images/product-basket/${item.image || item.img || ''}" alt="${item.name}" class="cart__img" style="width:${imgSize}px;height:${imgSize}px;object-fit:cover;">`}
<div class="cart__info">
<h4 class="cart__header">${item.name}</h4>
${!isMini && isMobile ? '' : `<p class="cart__description${isMini ? '' : ' cart__description--big'}">${item.description || ''}</p>`}
<span class="cart__price${isMini ? '' : ' cart__price--big'}">${(item.price).toLocaleString()} руб.</span>
<div class="cart__link-box" style="gap:${isMini ? 24 : 30}px;">
<a class="cart__link cart__link--favorite" href="#">Избранное</a>
<a class="cart__link cart__link--delete${isMini ? ' cart__link--delete-mini' : ''}" href="#">Удалить</a>
</div>
</div>
</div>
<input type="number" class="cart__value" value="${item.qty}" min="1" ${isMini ? 'disabled' : ''}>
</div>
`;
}
function renderCartItems() {
const container = document.getElementById('cart-items');
if (!container) return;
let cart = JSON.parse(localStorage.getItem('cart') || '[]');
if (cart.length === 0) {
container.innerHTML = '<div class="cart__empty">Ваша корзина пуста</div>';
updateCartUI();
return;
}
container.innerHTML = cart.map(item => cartItemTemplate(item, 'main')).join('');
updateCartUI();
}
// Пример сопоставления id товара и картинки (доработайте по необходимости)
function getCartImage(item) {
// Сопоставление id товара и картинки
const images = {
'1': 'Table-MENU.jpg', // Стол MENU
'2': 'Sofa-NASTAN.jpg', // Диван NASTAN
'3': 'Bed-TATRAN.jpg', // Кровать TATRAN
'4': 'Armchair-VILORA.jpg', // Кресло VILORA
'5': 'Table-NORMAN.jpg', // Стол NORMAN
'6': 'Sofa-ASKESTA.jpg', // Диван ASKESTA
// Добавьте другие товары по необходимости
};
// Сначала ищем в product-basket, если нет — в products
const basketPath = 'images/product-basket/' + (images[item.id] || '');
const productsPath = 'images/products/' + (images[item.id] || '');
// Проверяем, есть ли файл в product-basket (только для Table-MENU и Sofa-NASTAN)
if (['1','2'].includes(item.id)) return images[item.id];
// Для остальных — путь из products
return images[item.id] ? '../products/' + images[item.id] : 'Table-MENU.jpg';
}
// Удаление товара
if (window.location.pathname.includes('cart.html')) {
document.addEventListener('click', function(e) {
if (e.target.classList.contains('cart__link--delete')) {
e.preventDefault();
const item = e.target.closest('.cart__item');
if (item) {
let cart = JSON.parse(localStorage.getItem('cart') || '[]');
cart = cart.filter(i => i.id !== item.dataset.id);
localStorage.setItem('cart', JSON.stringify(cart));
renderCartItems();
}
}
if (e.target.classList.contains('cart__button--delete')) {
e.preventDefault();
localStorage.removeItem('cart');
renderCartItems();
}
});
// Изменение количества
document.addEventListener('input', function(e) {
if (e.target.classList.contains('cart__value')) {
const item = e.target.closest('.cart__item');
let cart = JSON.parse(localStorage.getItem('cart') || '[]');
const prod = cart.find(i => i.id === item.dataset.id);
if (prod) {
prod.qty = Math.max(1, parseInt(e.target.value, 10) || 1);
localStorage.setItem('cart', JSON.stringify(cart));
updateCartUI();
}
}
});
document.addEventListener('DOMContentLoaded', renderCartItems);
}
function renderMiniCart() {
const container = document.getElementById('mini-cart-items');
const totalEl = document.getElementById('mini-cart-total');
if (!container || !totalEl) return;
let cart = JSON.parse(localStorage.getItem('cart') || '[]');
if (cart.length === 0) {
container.innerHTML = '<div class="modal__item">Корзина пуста</div>';
totalEl.textContent = '0';
return;
}
// Показываем только первые 2 товара, если их больше
const showCount = 2;
let itemsHtml = cart.slice(0, showCount).map(item => cartItemTemplate(item, 'mini')).join('<hr class="modal__divider">');
// Если товаров больше 2, добавляем кнопку
if (cart.length > showCount) {
itemsHtml += `<button class="mini-cart__show-all" style="margin: 16px auto 0; display: block; width: 90%; padding: 8px 0; border-radius: 8px; border: 1px solid #3fa9f5; background: #f7f6f6; color: #3fa9f5; font-size: 15px; cursor: pointer;" onclick="window.location.href='cart.html'">Показать все товары</button>`;
}
container.innerHTML = itemsHtml;
totalEl.textContent = cart.reduce((sum, item) => sum + item.price * (item.qty || 1), 0).toLocaleString();
}
// Удаление товара из мини-корзины
if (typeof window !== 'undefined') {
document.addEventListener('click', function(e) {
if (e.target.classList.contains('cart__link--delete-mini')) {
e.preventDefault();
const item = e.target.closest('.cart__item');
if (item) {
let cart = JSON.parse(localStorage.getItem('cart') || '[]');
cart = cart.filter(i => i.id !== item.dataset.id);
localStorage.setItem('cart', JSON.stringify(cart));
renderCartItems();
renderMiniCart();
updateCartUI();
}
}
});
}
<script src="products.js"></script>