Proje Detayları

Adım Adım Geliştirme

Bu bölümde, e-ticaret uygulamasının sepet fonksiyonunu adım adım nasıl geliştirebileceğinizi öğreneceksiniz. Her adımda, ilgili kod parçalarını ve açıklamalarını bulacaksınız.

Adım 1: Proje Yapısını Oluşturma

İlk olarak, projemiz için gerekli dosyaları oluşturalım:

  • index.html - Ana HTML dosyası
  • style.css - CSS stil dosyası
  • script.js - JavaScript kod dosyası
  • products.js - Ürün verilerini içeren dosya
index.html
<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>E-Ticaret Uygulaması</title>
    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
</head>
<body>
    <div class="ecommerce-app">
        <div class="ecommerce-header">
            <h2>Demo Mağaza</h2>
            <div class="cart-icon" id="cartIcon">
                <i class="fas fa-shopping-cart"></i>
                <span class="cart-count" id="cartCount">0</span>
            </div>
        </div>
        
        <div class="product-list" id="productList">
            <!-- Ürünler buraya dinamik olarak eklenecek -->
        </div>
        
        <!-- Sepet Modalı -->
        <div id="cartModal" class="cart-modal">
            <div class="cart-content">
                <span class="close-cart-btn" id="closeCartBtn">×</span>
                <h2 class="cart-title">Alışveriş Sepeti</h2>
                <div class="cart-items" id="cartItems">
                    <!-- Sepet öğeleri buraya eklenecek -->
                </div>
                <div class="cart-total" id="cartTotal">Toplam: ₺0.00</div>
                <button class="checkout-btn" id="checkoutBtn">Ödemeye Geç</button>
            </div>
        </div>
    </div>

    <script src="products.js"></script>
    <script src="script.js"></script>
</body>
</html>
style.css
/* Genel Stiller */
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    background-color: #f0f2f5;
    color: #333;
    line-height: 1.6;
}

/* E-Ticaret Uygulaması Stilleri */
.ecommerce-app {
    max-width: 1200px;
    margin: 20px auto;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 0 10px rgba(0,0,0,0.1);
    overflow: hidden;
}

.ecommerce-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px 30px;
    background-color: #4caf50;
    color: white;
}

.ecommerce-header h2 {
    margin: 0;
    font-size: 1.8rem;
}

.cart-icon {
    position: relative;
    cursor: pointer;
}

.cart-icon i {
    font-size: 1.8rem;
}

.cart-count {
    position: absolute;
    top: -8px;
    right: -10px;
    background-color: #f44336;
    color: white;
    border-radius: 50%;
    padding: 3px 7px;
    font-size: 0.9rem;
    font-weight: bold;
}

.product-list {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 20px;
    padding: 30px;
}

.product-card {
    background-color: #fff;
    border: 1px solid #eee;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 5px rgba(0,0,0,0.05);
    transition: transform 0.3s, box-shadow 0.3s;
}

.product-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 15px rgba(0,0,0,0.1);
}

.product-image {
    width: 100%;
    height: 200px;
    object-fit: cover;
    display: block;
}

.product-info {
    padding: 15px;
}

.product-name {
    font-size: 1.2rem;
    font-weight: bold;
    margin-bottom: 10px;
    color: #333;
    height: 40px; /* İki satır için */
    overflow: hidden;
}

.product-price {
    font-size: 1.1rem;
    color: #4caf50;
    font-weight: bold;
    margin-bottom: 15px;
}

.add-to-cart-btn {
    display: block;
    width: 100%;
    padding: 10px;
    background-color: #4caf50;
    color: white;
    border: none;
    border-radius: 4px;
    font-size: 1rem;
    cursor: pointer;
    transition: background-color 0.3s;
}

.add-to-cart-btn:hover {
    background-color: #45a049;
}

.cart-modal {
    display: none;
    position: fixed;
    z-index: 1000;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    overflow: auto;
    background-color: rgba(0,0,0,0.5);
}

.cart-content {
    background-color: #fefefe;
    margin: 10% auto;
    padding: 30px;
    border: 1px solid #888;
    width: 90%;
    max-width: 700px;
    border-radius: 8px;
    position: relative;
    box-shadow: 0 5px 15px rgba(0,0,0,0.2);
}

.close-cart-btn {
    color: #aaa;
    position: absolute;
    top: 15px;
    right: 25px;
    font-size: 32px;
    font-weight: bold;
    cursor: pointer;
}

.close-cart-btn:hover,
.close-cart-btn:focus {
    color: black;
    text-decoration: none;
}

.cart-title {
    font-size: 1.8rem;
    margin-bottom: 25px;
    color: #333;
    text-align: center;
    border-bottom: 1px solid #eee;
    padding-bottom: 15px;
}

.cart-items {
    max-height: 400px;
    overflow-y: auto;
    margin-bottom: 20px;
    padding-right: 10px; /* Scrollbar için boşluk */
}

.cart-item {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
    padding-bottom: 15px;
    border-bottom: 1px solid #eee;
}

.cart-item:last-child {
    border-bottom: none;
    margin-bottom: 0;
}

.cart-item-image {
    width: 80px;
    height: 80px;
    object-fit: cover;
    margin-right: 20px;
    border-radius: 4px;
}

.cart-item-info {
    flex: 1;
}

.cart-item-name {
    font-weight: bold;
    margin-bottom: 5px;
    font-size: 1.1rem;
}

.cart-item-price {
    color: #666;
    margin-bottom: 10px;
}

.cart-item-quantity {
    display: flex;
    align-items: center;
}

.quantity-btn {
    background-color: #eee;
    border: 1px solid #ddd;
    padding: 5px 10px;
    cursor: pointer;
    font-size: 1rem;
    transition: background-color 0.2s;
}

.quantity-btn:hover {
    background-color: #ddd;
}

.quantity-input {
    width: 50px;
    text-align: center;
    border: 1px solid #ddd;
    margin: 0 5px;
    padding: 5px;
    font-size: 1rem;
}

.remove-item-btn {
    background: none;
    border: none;
    color: #f44336;
    font-size: 1.4rem;
    cursor: pointer;
    margin-left: 20px;
    transition: color 0.2s;
}

.remove-item-btn:hover {
    color: #c62828;
}

.cart-total {
    text-align: right;
    font-size: 1.3rem;
    font-weight: bold;
    margin: 20px 0;
    padding-top: 20px;
    border-top: 1px solid #eee;
}

.checkout-btn {
    display: block;
    width: 100%;
    padding: 15px;
    background-color: #4caf50;
    color: white;
    border: none;
    border-radius: 4px;
    font-size: 1.2rem;
    cursor: pointer;
    text-align: center;
    transition: background-color 0.3s;
}

.checkout-btn:hover {
    background-color: #45a049;
}

.empty-cart-message {
    text-align: center;
    color: #666;
    padding: 40px 20px;
    font-size: 1.1rem;
}

/* Responsive Tasarım */
@media (max-width: 768px) {
    .product-list {
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        padding: 20px;
    }
    
    .cart-content {
        width: 95%;
        margin: 5% auto;
        padding: 20px;
    }
    
    .cart-item {
        flex-direction: column;
        align-items: flex-start;
    }
    
    .cart-item-image {
        margin-bottom: 10px;
        margin-right: 0;
    }
    
    .remove-item-btn {
        margin-left: auto;
    }
}

@media (max-width: 480px) {
    .product-list {
        grid-template-columns: 1fr;
    }
    
    .ecommerce-header h2 {
        font-size: 1.5rem;
    }
    
    .cart-icon i {
        font-size: 1.5rem;
    }
}

Adım 2: Ürün Verilerini Oluşturma

Şimdi, mağazada gösterilecek ürün verilerini oluşturalım:

products.js
// Ürün verileri
const products = [
    {
        id: 1,
        name: "Rahat Pamuklu Tişört",
        price: 120.00,
        image: "https://via.placeholder.com/300x200/4caf50/ffffff?text=Tişört"
    },
    {
        id: 2,
        name: "Klasik Kot Pantolon",
        price: 350.00,
        image: "https://via.placeholder.com/300x200/2196f3/ffffff?text=Kot+Pantolon"
    },
    {
        id: 3,
        name: "Şık Spor Ayakkabı",
        price: 500.00,
        image: "https://via.placeholder.com/300x200/ff9800/ffffff?text=Ayakkabı"
    },
    {
        id: 4,
        name: "Güneş Gözlüğü",
        price: 250.00,
        image: "https://via.placeholder.com/300x200/f44336/ffffff?text=Gözlük"
    },
    {
        id: 5,
        name: "Deri Cüzdan",
        price: 180.00,
        image: "https://via.placeholder.com/300x200/9c27b0/ffffff?text=Cüzdan"
    },
    {
        id: 6,
        name: "Akıllı Saat",
        price: 1200.00,
        image: "https://via.placeholder.com/300x200/607d8b/ffffff?text=Saat"
    },
    {
        id: 7,
        name: "Kablosuz Kulaklık",
        price: 400.00,
        image: "https://via.placeholder.com/300x200/009688/ffffff?text=Kulaklık"
    },
    {
        id: 8,
        name: "Sırt Çantası",
        price: 300.00,
        image: "https://via.placeholder.com/300x200/795548/ffffff?text=Çanta"
    }
];

Adım 3: JavaScript Kodunu Yazma

Şimdi, uygulamanın işlevselliğini sağlayacak JavaScript kodunu yazalım:

script.js
// DOM elementlerini seçme
const productList = document.getElementById('productList');
const cartIcon = document.getElementById('cartIcon');
const cartCount = document.getElementById('cartCount');
const cartModal = document.getElementById('cartModal');
const closeCartBtn = document.getElementById('closeCartBtn');
const cartItems = document.getElementById('cartItems');
const cartTotal = document.getElementById('cartTotal');
const checkoutBtn = document.getElementById('checkoutBtn');

// Sepet verilerini LocalStorage'dan al veya boş bir dizi oluştur
let cart = JSON.parse(localStorage.getItem('cart')) || [];

// Sayfa yüklendiğinde
document.addEventListener('DOMContentLoaded', () => {
    // Ürünleri listele
    displayProducts();
    
    // Sepet ikonuna tıklama olayı
    cartIcon.addEventListener('click', openCartModal);
    
    // Sepet kapatma butonuna tıklama olayı
    closeCartBtn.addEventListener('click', closeCartModal);
    
    // Modal dışına tıklama olayı
    window.addEventListener('click', (event) => {
        if (event.target === cartModal) {
            closeCartModal();
        }
    });
    
    // Ürün listesine tıklama olayı (event delegation)
    productList.addEventListener('click', (event) => {
        if (event.target.classList.contains('add-to-cart-btn')) {
            const productId = parseInt(event.target.dataset.id);
            addToCart(productId);
        }
    });
    
    // Sepet öğelerine tıklama olayı (event delegation)
    cartItems.addEventListener('click', (event) => {
        const target = event.target;
        const productId = parseInt(target.closest('.cart-item').dataset.id);
        
        if (target.classList.contains('increase-quantity')) {
            updateQuantity(productId, 1);
        } else if (target.classList.contains('decrease-quantity')) {
            updateQuantity(productId, -1);
        } else if (target.classList.contains('remove-item-btn')) {
            removeFromCart(productId);
        }
    });
    
    // Sepet miktar girişine değişiklik olayı (event delegation)
    cartItems.addEventListener('change', (event) => {
        if (event.target.classList.contains('quantity-input')) {
            const productId = parseInt(event.target.closest('.cart-item').dataset.id);
            const newQuantity = parseInt(event.target.value);
            setQuantity(productId, newQuantity);
        }
    });
    
    // Ödeme butonuna tıklama olayı
    checkoutBtn.addEventListener('click', () => {
        alert('Ödeme işlemi henüz tamamlanmadı!');
        // Gerçek bir uygulamada burada ödeme sayfasına yönlendirme yapılır.
    });
    
    // Sepeti güncelle (sayfa yüklendiğinde)
    updateCartDisplay();
});

// Ürünleri gösterme fonksiyonu
function displayProducts() {
    productList.innerHTML = ''; // Önceki ürünleri temizle
    products.forEach(product => {
        const productCard = document.createElement('div');
        productCard.className = 'product-card';
        productCard.innerHTML = `
            
            
                ${product.name}${product.price.toFixed(2)}
                Sepete Ekle
            
        `;
        productList.appendChild(productCard);
    });
}

// Sepete ürün ekleme fonksiyonu
function addToCart(productId) {
    // Ürünü bul
    const productToAdd = products.find(p => p.id === productId);
    
    // Sepette ürün var mı kontrol et
    const existingCartItem = cart.find(item => item.id === productId);
    
    if (existingCartItem) {
        // Ürün zaten sepetteyse, miktarını artır
        existingCartItem.quantity++;
    } else {
        // Ürün sepette yoksa, yeni öğe olarak ekle
        cart.push({ ...productToAdd, quantity: 1 });
    }
    
    // Sepeti güncelle
    updateCartDisplay();
    saveCartToLocalStorage();
    
    // Kullanıcıya geri bildirim ver (isteğe bağlı)
    showNotification(`${productToAdd.name} sepete eklendi.`);
}

// Sepetten ürün çıkarma fonksiyonu
function removeFromCart(productId) {
    cart = cart.filter(item => item.id !== productId);
    updateCartDisplay();
    saveCartToLocalStorage();
}

// Ürün miktarını güncelleme fonksiyonu
function updateQuantity(productId, change) {
    const cartItem = cart.find(item => item.id === productId);
    if (cartItem) {
        cartItem.quantity += change;
        if (cartItem.quantity <= 0) {
            // Miktar 0 veya daha az ise ürünü sepetten çıkar
            removeFromCart(productId);
        } else {
            updateCartDisplay();
            saveCartToLocalStorage();
        }
    }
}

// Ürün miktarını ayarlama fonksiyonu
function setQuantity(productId, newQuantity) {
    const cartItem = cart.find(item => item.id === productId);
    if (cartItem) {
        if (newQuantity > 0) {
            cartItem.quantity = newQuantity;
            updateCartDisplay();
            saveCartToLocalStorage();
        } else {
            // Geçersiz miktar girilirse (0 veya negatif), ürünü çıkar
            removeFromCart(productId);
        }
    }
}

// Sepet gösterimini güncelleme fonksiyonu
function updateCartDisplay() {
    // Sepet ikonundaki sayıyı güncelle
    const totalItems = cart.reduce((sum, item) => sum + item.quantity, 0);
    cartCount.textContent = totalItems;
    
    // Sepet modal içeriğini güncelle
    cartItems.innerHTML = ''; // Önceki öğeleri temizle
    
    if (cart.length === 0) {
        cartItems.innerHTML = 'Sepetiniz boş.';
        cartTotal.textContent = 'Toplam: ₺0.00';
        checkoutBtn.disabled = true;
    } else {
        let total = 0;
        cart.forEach(item => {
            const cartItemElement = document.createElement('div');
            cartItemElement.className = 'cart-item';
            cartItemElement.dataset.id = item.id;
            cartItemElement.innerHTML = `
                
                
                    ${item.name}${item.price.toFixed(2)}
                    
                        -
                        
                        +
                    
                
                
            `;
            cartItems.appendChild(cartItemElement);
            total += item.price * item.quantity;
        });
        
        cartTotal.textContent = `Toplam: ₺${total.toFixed(2)}`;
        checkoutBtn.disabled = false;
    }
}

// Sepeti LocalStorage'a kaydetme fonksiyonu
function saveCartToLocalStorage() {
    localStorage.setItem('cart', JSON.stringify(cart));
}

// Sepet modalını açma fonksiyonu
function openCartModal() {
    updateCartDisplay(); // Modalı açmadan önce içeriği güncelle
    cartModal.style.display = 'block';
}

// Sepet modalını kapatma fonksiyonu
function closeCartModal() {
    cartModal.style.display = 'none';
}

// Bildirim gösterme fonksiyonu (isteğe bağlı)
function showNotification(message) {
    // Basit bir alert kullanabilir veya daha gelişmiş bir bildirim sistemi oluşturabilirsiniz.
    // Örneğin: Toastify.js, SweetAlert2 vb.
    console.log(message); // Şimdilik konsola yazdır
    
    // Geçici bir bildirim elementi oluşturup gösterebilirsiniz
    const notification = document.createElement('div');
    notification.className = 'notification';
    notification.textContent = message;
    document.body.appendChild(notification);
    
    // Bildirimi birkaç saniye sonra kaldır
    setTimeout(() => {
        notification.remove();
    }, 3000);
    
    // Bildirim için CSS ekleyin:
    /*
    .notification {
        position: fixed;
        bottom: 20px;
        left: 50%;
        transform: translateX(-50%);
        background-color: rgba(0, 0, 0, 0.7);
        color: white;
        padding: 10px 20px;
        border-radius: 5px;
        z-index: 1001;
        opacity: 0;
        animation: fadeinout 3s ease-in-out;
    }
    @keyframes fadeinout {
        0%, 100% { opacity: 0; }
        10%, 90% { opacity: 1; }
    }
    */
}

Adım 4: Uygulamayı Test Etme

Şimdi uygulamanızı test etme zamanı! Aşağıdaki adımları izleyin:

  1. Tüm dosyaları (index.htmlstyle.cssscript.jsproducts.js) aynı klasöre kaydedin.
  2. HTML dosyasını bir web tarayıcısında açın.
  3. Ürünlerin listelendiğini doğrulayın.
  4. "Sepete Ekle" butonlarına tıklayarak ürünleri sepete ekleyin.
  5. Sepet ikonundaki sayının güncellendiğini kontrol edin.
  6. Sepet ikonuna tıklayarak sepet modalını açın.
  7. Sepet içeriğini, miktarları ve toplam tutarı kontrol edin.
  8. Miktarları artırıp azaltmayı ve ürünleri sepetten çıkarmayı deneyin.
  9. Sayfayı yenileyin ve sepetin LocalStorage sayesinde korunduğunu doğrulayın.

İpucu: Tarayıcınızın geliştirici araçlarını (genellikle F12 tuşu ile açılır) kullanarak LocalStorage içeriğini inceleyebilir ve JavaScript hatalarını ayıklayabilirsiniz.

Projeyi Geliştirme

Temel e-ticaret sepet fonksiyonunu başarıyla oluşturduktan sonra, aşağıdaki özelliklerle projenizi geliştirebilirsiniz:

1. Ürün Detay Sayfası

Her ürün için ayrı bir detay sayfası oluşturun. Kullanıcılar ürün kartına tıkladığında bu sayfaya yönlendirilsin ve ürün hakkında daha fazla bilgi (açıklama, özellikler, yorumlar vb.) görebilsin.

2. Filtreleme ve Sıralama

Ürünleri kategoriye, fiyata veya popülerliğe göre filtreleme ve sıralama özellikleri ekleyin.

3. Arama Fonksiyonu

Kullanıcıların ürünleri isme göre arayabilmesini sağlayan bir arama çubuğu ekleyin.

4. Kullanıcı Hesapları

Kullanıcıların hesap oluşturup giriş yapabilmesini sağlayın. Sepetlerini hesaplarına kaydedebilirler.

5. Ödeme Entegrasyonu

Gerçek bir ödeme sistemi (örneğin, Stripe, PayPal) entegre ederek kullanıcıların siparişlerini tamamlamasını sağlayın. (Bu genellikle sunucu tarafı kodlama gerektirir.)

6. Favori Ürünler

Kullanıcıların beğendikleri ürünleri favorilerine ekleyebilmesini sağlayan bir özellik ekleyin.

Geliştirme Zorlukları

E-ticaret uygulamanızı daha da geliştirmek için aşağıdaki zorlukları deneyebilirsiniz:

  1. Stok Yönetimi: Ürünlerin stok durumunu takip edin ve stokta olmayan ürünlerin sepete eklenmesini engelleyin.
  2. İndirim Kuponları: Kullanıcıların indirim kuponları kullanabilmesini sağlayan bir sistem ekleyin.
  3. Ürün Yorumları ve Puanlama: Kullanıcıların ürünlere yorum yapabilmesini ve puan verebilmesini sağlayın.
  4. İlgili Ürünler: Ürün detay sayfasında veya sepette ilgili ürünleri önerin.
  5. Animasyonlar: Sepete ekleme veya sepetten çıkarma gibi işlemlerde görsel geri bildirim için animasyonlar kullanın.

Sonuç ve Öğrenilen Dersler

Bu projede, JavaScript kullanarak basit bir e-ticaret uygulamasının sepet fonksiyonunu geliştirdik. Bu süreçte şunları öğrendik:

  • Ürün verilerini dinamik olarak DOM'a yüklemeyi
  • Sepete ekleme, çıkarma ve miktar güncelleme işlevselliği oluşturmayı
  • Sepet içeriğini LocalStorage kullanarak kalıcı hale getirmeyi
  • Sepet miktarını ve toplam tutarı hesaplamayı
  • Modal (açılır pencere) oluşturmayı ve yönetmeyi
  • Olay yetkilendirme (event delegation) tekniğini kullanmayı
  • Responsive tasarım ilkelerini uygulamayı

Bu proje, modern web geliştirme becerilerinizi geliştirmenize ve gerçek dünya uygulamaları oluşturmanıza yardımcı olacak temel bilgileri sağlamıştır. Öğrendiğiniz teknikleri ve kavramları kullanarak, daha karmaşık ve tam özellikli e-ticaret platformları geliştirebilirsiniz.