// Ürün fiyatları (örneğin, gramaj başına fiyatlar)
const prices = {
'30 GR':1,
'50 GR': 1,
'100 GR': 1,
'125 GR': 1,
'250 GR': 1
};
// Mevcut quantity değeri ve seçilen gramaj fiyatını depolamak için değişkenler
let currentQuantity = 1;
let selectedPrice = 0;
let selectedGram = '30 GR'; // Varsayılan olarak ilk gramaj
let selectedImageSrc = ''; // Seçilen ürün resmi
// Tüm size-item sınıfına sahip elemanları seçin
const sizeItems = document.querySelectorAll('.size-item');
const sizeValueText = document.querySelector('.size-value');
const cartCountText = document.querySelector('.cart-count');
const quantityElement = document.querySelector('.center-number');
const addToCartButtons = document.querySelectorAll('.add-to-cart'); // Sepete Ekle butonlarını seçin
const productImageElement = document.querySelector('.slider-image'); // Ürün resmini seçin
// İlk gramajı varsayılan olarak seç
document.addEventListener('DOMContentLoaded', () => {
const defaultSizeItem = document.querySelector('.size-item');
if (defaultSizeItem) {
defaultSizeItem.classList.add('active');
selectedPrice = prices[selectedGram];
selectedImageSrc = productImageElement ? productImageElement.src : ''; // Varsayılan resim
updatePriceDisplay();
updateSelectedAttributes(); // Varsayılan seçimi ve resmi güncelle
}
});
// Her bir size-item için tıklama olayını ekleyin
sizeItems.forEach(item => {
item.addEventListener('click', () => {
// Seçilen gramajı al ve fiyatını belirle
selectedGram = item.querySelector('.size-item-gr').textContent.trim();
selectedPrice = prices[selectedGram];
// Ürün resminin src değerini al
selectedImageSrc = productImageElement ? productImageElement.src : '';
// Size ve Add to Cart değerlerini güncelle
updatePriceDisplay();
// Tüm butonların aktif sınıfını temizleyip seçilene ekleyin
sizeItems.forEach(btn => btn.classList.remove('active'));
item.classList.add('active');
// Seçilen gramajı ve resmi 'Add to Cart' butonlarına ekleyin
updateSelectedAttributes();
});
// CSS sınıfı için gerekli olan stil
const style = document.createElement('style');
style.textContent = `
.size-item.active {
background-color: black;
color: white;
}
.size-item.active .size-item-gr,
.size-item.active .size-item-text {
color: white;
}
`;
document.head.appendChild(style);
// Minus ve Plus butonları için olay dinleyiciler
const minusBox = document.querySelector('.minus-box');
if (minusBox) {
minusBox.addEventListener('click', () => {
if (currentQuantity > 1) {
currentQuantity--;
updatePriceDisplay();
}
const plusBox = document.querySelector('.plus-box');
if (plusBox) {
plusBox.addEventListener('click', () => {
currentQuantity++;
updatePriceDisplay();
// Fiyatı ve quantity'yi güncelleyen fonksiyon
function updatePriceDisplay() {
const totalPrice = selectedPrice * currentQuantity;
sizeValueText.textContent = `${totalPrice} USD`;
cartCountText.textContent = `${totalPrice} USD`;
quantityElement.textContent = currentQuantity;
}
function updateSelectedAttributes() {
addToCartButtons.forEach(button => {
button.setAttribute('selected-gr', selectedGram);
button.setAttribute('product-image', selectedImageSrc); // Ürün resmini güncelle
});
}
// Sepet verilerini saklamak için bir anahtar tanımlayın
const CART_STORAGE_KEY = 'shoppingCart';
// Sayfa yüklendiğinde sepeti yükleyin
window.addEventListener('load', () => {
loadCart();
updateSelectedAttributes(); // İlk yükleme sırasında seçili gramajı ve resmi güncelle
});
// Sepete Ekle düğmelerine tıklama olayı ekleyin
addToCartButtons.forEach(button => {
button.addEventListener('click', (event) => {
// Default link tıklamasını engelle
event.preventDefault();
// Eğer gramaj seçilmemişse işlemi durdur
if (!selectedGram) {
alert('Lütfen bir gramaj seçin!');
return;
}
// Ürün bilgilerini al
const productName = button.getAttribute('product-title');
const productId = button.getAttribute('product-id');
const productImage = button.getAttribute('product-image'); // Ürün resmini al
// 'cart-count' içindeki değeri ve product-price özniteliğini al
const cartCountElement = button.querySelector('.cart-count');
const cartCountText = cartCountElement ? cartCountElement.textContent.replace('USD', '').trim() : '';
const productPrice = parseFloat(cartCountText) || parseFloat(button.getAttribute('product-price'));
// Aktif olan gramajı al
const selectedSizeElement = document.querySelector('.size-item.w-inline-block.active');
const productSize = selectedSizeElement ? selectedSizeElement.querySelector('.size-item-gr').textContent.trim() : 'Default Size';
// Miktar alanındaki değeri al
const quantityElement = document.querySelector('.quantity-box .center-number'); // Quantity input'u seç
const quantity = quantityElement ? parseInt(quantityElement.textContent.trim()) : 1;
console.log('Ürün Bilgileri:', { productName, productPrice, productId, productSize, productImage, quantity });
// Ürünü sepete ekle
addToCart(productId, productName, productSize, productPrice, quantity, productImage);
});
});
// Sepete ürün ekleme fonksiyonu
function addToCart(id, name, size, price, quantity, image) {
const cartItemsContainer = document.querySelector('.list-box');
// localStorage'dan mevcut sepeti al
let cart = JSON.parse(localStorage.getItem(CART_STORAGE_KEY)) || [];
// Sepette bu ürün ve gramaj var mı kontrol et
let existingProduct = cart.find(item => item.id === id && item.size === size);
if (existingProduct) {
// Ürün ve gramaj zaten sepette, miktarı artır
existingProduct.quantity += quantity;
} else {
// Ürün sepette yok, yeni ürün ekle
cart.push({ id, name, size, price, quantity, image });
}
// Güncellenmiş sepeti localStorage'da sakla
localStorage.setItem(CART_STORAGE_KEY, JSON.stringify(cart));
// Sepeti görsel olarak güncelle
renderCart();
updateCartTotal(); // Sepet toplamını güncelle
}
// Sepeti görsel olarak oluşturma fonksiyonu
function renderCart() {
const cartItemsContainer = document.querySelector('.list-box');
cartItemsContainer.innerHTML = ''; // Mevcut içeriği temizle
// localStorage'dan mevcut sepeti al
let cart = JSON.parse(localStorage.getItem(CART_STORAGE_KEY)) || [];
if (cart.length === 0) {
cartItemsContainer.innerHTML = '
Sepette ürün yok.
'; // Sepet boşsa mesaj göster
return;
}
// Her bir ürün için HTML oluştur
cart.forEach(item => {
const cartItem = document.createElement('div');
cartItem.classList.add('product-list-cart');
cartItem.setAttribute('data-product-id', item.id); // Ürünün kimliğini sepete ekleyin
cartItem.innerHTML = `
${item.name} - ${item.size}
${(item.price * item.quantity).toFixed(2)} USD
X
`;
cartItemsContainer.appendChild(cartItem);
// Sepet öğesi olaylarını ekleyin
setupCartItemEvents(cartItem, item.id, item.size);
});
}
// Sepet öğesi için olay dinleyicilerini ayarla
function setupCartItemEvents(cartItem, id, size) {
// Silme işlevselliği
cartItem.querySelector('.remove-cart-x').addEventListener('click', () => {
removeFromCart(id, size);
});
// Miktar azaltma işlevselliği
cartItem.querySelector('.minus-box').addEventListener('click', () => {
updateQuantity(id, size, -1);
});
// Miktar artırma işlevselliği
cartItem.querySelector('.plus-box').addEventListener('click', () => {
updateQuantity(id, size, 1);
});
}
// Sepetten ürün çıkarma fonksiyonu
function removeFromCart(id, size) {
let cart = JSON.parse(localStorage.getItem(CART_STORAGE_KEY)) || [];
cart = cart.filter(item => !(item.id === id && item.size === size)); // Ürünü ve boyutu çıkar
localStorage.setItem(CART_STORAGE_KEY, JSON.stringify(cart)); // Güncellenmiş sepeti sakla
renderCart(); // Sepeti güncelle
updateCartTotal(); // Sepet toplamını güncelle
}
// Miktarı güncelleme fonksiyonu
function updateQuantity(id, size, change) {
let cart = JSON.parse(localStorage.getItem(CART_STORAGE_KEY)) || [];
let existingProduct = cart.find(item => item.id === id && item.size === size);
if (existingProduct) {
existingProduct.quantity += change;
if (existingProduct.quantity <= 0) {
removeFromCart(id, size); // Miktar 0 veya negatif olursa ürünü çıkar
} else {
localStorage.setItem(CART_STORAGE_KEY, JSON.stringify(cart)); // Güncellenmiş sepeti sakla
renderCart(); // Sepeti güncelle
updateCartTotal(); // Sepet toplamını güncelle
}
}
}
// Sepet toplamını güncelle
function updateCartTotal() {
const cart = JSON.parse(localStorage.getItem(CART_STORAGE_KEY)) || [];
let total = 0;
cart.forEach(item => {
total += item.price * item.quantity;
});
document.querySelector('.cart-total-total').textContent = `${total.toFixed(2)} USD`;
}
// Sayfa yüklendiğinde sepeti yükleme fonksiyonu
function loadCart() {
renderCart();
updateCartTotal();
}