Aleksmorshen commited on
Commit
fbfcc14
·
verified ·
1 Parent(s): 386e465

Update script.js

Browse files
Files changed (1) hide show
  1. script.js +67 -43
script.js CHANGED
@@ -94,35 +94,48 @@ window.addEventListener('resize', () => {
94
  let cart = JSON.parse(localStorage.getItem('cart')) || [];
95
 
96
  function updateCart() {
 
97
  localStorage.setItem('cart', JSON.stringify(cart));
 
 
98
  const cartCount = document.getElementById('cartCount');
99
- cartCount.textContent = cart.length;
 
 
100
 
 
101
  const cartItems = document.getElementById('cartItems');
102
- cartItems.innerHTML = '';
103
- if (cart.length === 0) {
104
- cartItems.innerHTML = '<li>Корзина пуста</li>';
105
- } else {
106
- cart.forEach(item => {
107
- const li = document.createElement('li');
108
- li.textContent = item;
109
- cartItems.appendChild(li);
110
- });
 
 
111
  }
112
  }
113
 
114
- // Убедимся, что кнопки добавления в корзину работают
115
- document.addEventListener('DOMContentLoaded', () => {
116
- document.querySelectorAll('.add-to-cart-btn').forEach(button => {
117
- button.addEventListener('click', () => {
 
 
 
118
  const serviceCard = button.closest('.service-card');
119
  const serviceName = serviceCard.getAttribute('data-service');
120
- if (!cart.includes(serviceName)) {
121
  cart.push(serviceName);
122
  updateCart();
123
  alert(`${serviceName} добавлено в корзину!`);
124
- } else {
125
  alert(`${serviceName} уже в корзине!`);
 
 
126
  }
127
  });
128
  });
@@ -132,36 +145,47 @@ document.addEventListener('DOMContentLoaded', () => {
132
  const cartModal = document.getElementById('cartModal');
133
  const closeModal = document.getElementById('closeModal');
134
 
135
- cartIcon.addEventListener('click', () => {
136
- cartModal.style.display = 'flex';
137
- updateCart();
138
- });
 
139
 
140
- closeModal.addEventListener('click', () => {
141
- cartModal.style.display = 'none';
142
- });
 
143
 
144
  // Очистка корзины
145
- document.getElementById('clearCartBtn').addEventListener('click', () => {
146
- cart = [];
147
- updateCart();
148
- alert('Корзина очищена!');
149
- });
 
 
 
150
 
151
  // Рассчитать стоимость
152
- document.getElementById('calculateBtn').addEventListener('click', () => {
153
- if (cart.length > 0) {
154
- const message = `Здравствуйте! Интересуют следующие услуги: ${cart.join(', ')}. Прошу рассчитать стоимость.`;
155
- const whatsappUrl = `https://wa.me/996500398754?text=${encodeURIComponent(message)}`;
156
- window.open(whatsappUrl, '_blank');
157
- cartModal.style.display = 'none';
158
- cart = []; // Очищаем корзину после отправки
159
- updateCart();
160
- } else {
161
- alert('Пожалуйста, выберите хотя бы одну услугу!');
162
- }
163
- });
164
- });
 
 
 
165
 
166
- // Инициализация корзины при загрузке страницы
167
- updateCart();
 
 
 
 
94
  let cart = JSON.parse(localStorage.getItem('cart')) || [];
95
 
96
  function updateCart() {
97
+ // Сохраняем корзину в Local Storage
98
  localStorage.setItem('cart', JSON.stringify(cart));
99
+
100
+ // Обновляем счетчик корзины
101
  const cartCount = document.getElementById('cartCount');
102
+ if (cartCount) {
103
+ cartCount.textContent = cart.length;
104
+ }
105
 
106
+ // Обновляем содержимое модального окна
107
  const cartItems = document.getElementById('cartItems');
108
+ if (cartItems) {
109
+ cartItems.innerHTML = '';
110
+ if (cart.length === 0) {
111
+ cartItems.innerHTML = '<li>Корзина пуста</li>';
112
+ } else {
113
+ cart.forEach(item => {
114
+ const li = document.createElement('li');
115
+ li.textContent = item;
116
+ cartItems.appendChild(li);
117
+ });
118
+ }
119
  }
120
  }
121
 
122
+ // Функция для привязки событий
123
+ function initializeCart() {
124
+ // Привязываем события к кнопкам "Добавить в корзину"
125
+ const addToCartButtons = document.querySelectorAll('.add-to-cart-btn');
126
+ addToCartButtons.forEach(button => {
127
+ button.addEventListener('click', (e) => {
128
+ e.preventDefault(); // Предотвращаем возможные конфликты
129
  const serviceCard = button.closest('.service-card');
130
  const serviceName = serviceCard.getAttribute('data-service');
131
+ if (serviceName && !cart.includes(serviceName)) {
132
  cart.push(serviceName);
133
  updateCart();
134
  alert(`${serviceName} добавлено в корзину!`);
135
+ } else if (cart.includes(serviceName)) {
136
  alert(`${serviceName} уже в корзине!`);
137
+ } else {
138
+ console.error('Не удалось определить услугу для добавления в корзину');
139
  }
140
  });
141
  });
 
145
  const cartModal = document.getElementById('cartModal');
146
  const closeModal = document.getElementById('closeModal');
147
 
148
+ if (cartIcon && cartModal && closeModal) {
149
+ cartIcon.addEventListener('click', () => {
150
+ cartModal.style.display = 'flex';
151
+ updateCart();
152
+ });
153
 
154
+ closeModal.addEventListener('click', () => {
155
+ cartModal.style.display = 'none';
156
+ });
157
+ }
158
 
159
  // Очистка корзины
160
+ const clearCartBtn = document.getElementById('clearCartBtn');
161
+ if (clearCartBtn) {
162
+ clearCartBtn.addEventListener('click', () => {
163
+ cart = [];
164
+ updateCart();
165
+ alert('Корзина очищена!');
166
+ });
167
+ }
168
 
169
  // Рассчитать стоимость
170
+ const calculateBtn = document.getElementById('calculateBtn');
171
+ if (calculateBtn) {
172
+ calculateBtn.addEventListener('click', () => {
173
+ if (cart.length > 0) {
174
+ const message = `Здравствуйте! Интересуют следующие услуги: ${cart.join(', ')}. Прошу рассчитать стоимость.`;
175
+ const whatsappUrl = `https://wa.me/996500398754?text=${encodeURIComponent(message)}`;
176
+ window.open(whatsappUrl, '_blank');
177
+ cartModal.style.display = 'none';
178
+ cart = []; // Очищаем корзину после отправки
179
+ updateCart();
180
+ } else {
181
+ alert('Пожалуйста, выберите хотя бы одну услугу!');
182
+ }
183
+ });
184
+ }
185
+ }
186
 
187
+ // Инициализация корзины после загрузки DOM
188
+ document.addEventListener('DOMContentLoaded', () => {
189
+ initializeCart();
190
+ updateCart();
191
+ });