nxpwebsite / script.js
mortabeatss's picture
Upload 7 files
d270dcc verified
Raw History Blame Contribute Delete
23.4 kB
// Shopping Cart Management
let cart = [];
let cartTotalAmount = 0;
// Product Data
const products = {
'classic-tee': {
name: 'Classic Cotton Tee',
price: 24.99,
description: '100% cotton, comfortable fit. Available in multiple colors and sizes.',
features: ['100% Cotton', 'Pre-shrunk', 'Machine Washable', 'Comfortable Fit'],
sizes: ['XS', 'S', 'M', 'L', 'XL', 'XXL'],
colors: ['Black', 'White', 'Navy', 'Gray', 'Red']
},
'premium-tee': {
name: 'Premium Blend Tee',
price: 29.99,
description: 'Soft cotton-poly blend for ultimate comfort and durability.',
features: ['Cotton-Poly Blend', 'Moisture Wicking', 'Fade Resistant', 'Tagless'],
sizes: ['XS', 'S', 'M', 'L', 'XL', 'XXL'],
colors: ['Black', 'White', 'Heather Gray', 'Navy', 'Burgundy']
},
'athletic-shorts': {
name: 'Athletic Shorts',
price: 34.99,
description: 'Moisture-wicking fabric perfect for workouts and active lifestyle.',
features: ['Moisture Wicking', 'Quick Dry', 'Elastic Waistband', 'Side Pockets'],
sizes: ['S', 'M', 'L', 'XL', 'XXL'],
colors: ['Black', 'Navy', 'Gray', 'Royal Blue']
},
'casual-shorts': {
name: 'Casual Shorts',
price: 27.99,
description: 'Comfortable everyday wear with a relaxed fit.',
features: ['Cotton Blend', 'Relaxed Fit', 'Multiple Pockets', 'Belt Loops'],
sizes: ['S', 'M', 'L', 'XL', 'XXL'],
colors: ['Khaki', 'Navy', 'Black', 'Olive']
},
'tote-bag': {
name: 'Canvas Tote Bag',
price: 19.99,
description: 'Durable canvas material perfect for shopping and everyday use.',
features: ['Heavy-duty Canvas', 'Reinforced Handles', 'Large Capacity', 'Eco-friendly'],
sizes: ['One Size'],
colors: ['Natural', 'Black', 'Navy', 'Red']
},
'backpack': {
name: 'Urban Backpack',
price: 49.99,
description: 'Multi-compartment design perfect for work, school, or travel.',
features: ['Multiple Compartments', 'Laptop Sleeve', 'Water Resistant', 'Padded Straps'],
sizes: ['One Size'],
colors: ['Black', 'Gray', 'Navy', 'Olive']
},
'gym-duffle': {
name: 'Gym Duffle Bag',
price: 59.99,
description: 'Perfect for workouts with separate shoe compartment.',
features: ['Shoe Compartment', 'Water Resistant', 'Adjustable Strap', 'Side Pockets'],
sizes: ['Medium', 'Large'],
colors: ['Black', 'Navy', 'Gray', 'Red']
},
'travel-duffle': {
name: 'Travel Duffle Bag',
price: 79.99,
description: 'Large capacity for trips with durable construction.',
features: ['Large Capacity', 'Durable Material', 'Wheels Available', 'Multiple Handles'],
sizes: ['Large', 'Extra Large'],
colors: ['Black', 'Navy', 'Brown', 'Gray']
},
'beach-flops': {
name: 'Beach Flip Flops',
price: 19.99,
description: 'Comfortable rubber sole perfect for beach and casual wear.',
features: ['Rubber Sole', 'Comfortable Straps', 'Non-slip', 'Water Resistant'],
sizes: ['6', '7', '8', '9', '10', '11', '12'],
colors: ['Black', 'Blue', 'Red', 'White']
},
'premium-flops': {
name: 'Premium Flip Flops',
price: 29.99,
description: 'Cushioned footbed for all-day comfort.',
features: ['Cushioned Footbed', 'Arch Support', 'Durable Straps', 'Non-slip Sole'],
sizes: ['6', '7', '8', '9', '10', '11', '12'],
colors: ['Black', 'Brown', 'Navy', 'Tan']
}
};
// DOM Elements
const cartSidebar = document.getElementById('cart-sidebar');
const cartItems = document.getElementById('cart-items');
const cartTotal = document.getElementById('cart-total');
const cartCount = document.querySelector('.cart-count');
const productModal = document.getElementById('product-modal');
const modalBody = document.getElementById('modal-body');
// Initialize
document.addEventListener('DOMContentLoaded', function() {
updateCartDisplay();
initializeAnimations();
initializeSmoothScrolling();
initializeSearch();
initializeFAQ();
initializeNewsletter();
initializeContactForm();
handleCategoryFromURL(); // Handle category filtering from URL
});
// Smooth Scrolling
function initializeSmoothScrolling() {
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
anchor.addEventListener('click', function (e) {
e.preventDefault();
const target = document.querySelector(this.getAttribute('href'));
if (target) {
target.scrollIntoView({
behavior: 'smooth',
block: 'start'
});
}
});
});
}
// Scroll to Products
function scrollToProducts() {
document.getElementById('products').scrollIntoView({
behavior: 'smooth',
block: 'start'
});
}
// Animation on Scroll
function initializeAnimations() {
const observerOptions = {
threshold: 0.1,
rootMargin: '0px 0px -50px 0px'
};
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.classList.add('visible');
}
});
}, observerOptions);
document.querySelectorAll('.product-card, .featured-card, .feature').forEach(el => {
el.classList.add('fade-in');
observer.observe(el);
});
}
// Mobile Menu Toggle
function toggleMobileMenu() {
const navMenu = document.querySelector('.nav-menu');
navMenu.classList.toggle('active');
}
// Cart Functions
function toggleCart() {
cartSidebar.classList.toggle('open');
}
function addToCart(productId, productName, price) {
const existingItem = cart.find(item => item.id === productId);
if (existingItem) {
existingItem.quantity += 1;
} else {
cart.push({
id: productId,
name: productName,
price: price,
quantity: 1
});
}
updateCartDisplay();
showNotification(`${productName} added to cart!`);
}
function removeFromCart(productId) {
cart = cart.filter(item => item.id !== productId);
updateCartDisplay();
}
function updateQuantity(productId, change) {
const item = cart.find(item => item.id === productId);
if (item) {
item.quantity += change;
if (item.quantity <= 0) {
removeFromCart(productId);
} else {
updateCartDisplay();
}
}
}
function updateCartDisplay() {
// Update cart count
const totalItems = cart.reduce((sum, item) => sum + item.quantity, 0);
cartCount.textContent = totalItems;
// Update cart total
cartTotalAmount = cart.reduce((sum, item) => sum + (item.price * item.quantity), 0);
document.getElementById('cart-total').textContent = cartTotalAmount.toFixed(2);
// Update cart items
if (cart.length === 0) {
cartItems.innerHTML = '<p class="empty-cart">Your cart is empty</p>';
} else {
cartItems.innerHTML = cart.map(item => `
<div class="cart-item">
<div class="cart-item-image">
<i class="fas fa-tshirt"></i>
</div>
<div class="cart-item-info">
<div class="cart-item-name">${item.name}</div>
<div class="cart-item-price">$${item.price.toFixed(2)}</div>
<div class="cart-item-quantity">
<button class="quantity-btn" onclick="updateQuantity('${item.id}', -1)">-</button>
<span>${item.quantity}</span>
<button class="quantity-btn" onclick="updateQuantity('${item.id}', 1)">+</button>
</div>
</div>
<button class="remove-item" onclick="removeFromCart('${item.id}')">
<i class="fas fa-trash"></i>
</button>
</div>
`).join('');
}
}
// Product Filter
function filterProducts(category) {
console.log('Filtering products by category:', category); // Debug log
const productCards = document.querySelectorAll('.product-card');
const filterBtns = document.querySelectorAll('.filter-btn');
// Update active filter button
filterBtns.forEach(btn => btn.classList.remove('active'));
// Find and activate the correct button
filterBtns.forEach(btn => {
if (btn.textContent.toLowerCase().includes(category.replace('-', ' ')) ||
(category === 'tshirts' && btn.textContent.toLowerCase().includes('t-shirt')) ||
(category === 'all' && btn.textContent.toLowerCase().includes('all'))) {
btn.classList.add('active');
}
});
// Filter products
productCards.forEach(card => {
const cardCategory = card.dataset.category;
console.log('Card category:', cardCategory, 'Filter category:', category); // Debug log
if (category === 'all' || cardCategory === category) {
card.style.display = 'block';
card.classList.add('visible');
} else {
card.style.display = 'none';
card.classList.remove('visible');
}
});
}
// Handle URL hash changes for direct category links
function handleCategoryFromURL() {
const hash = window.location.hash.substring(1); // Remove the # symbol
console.log('Handling URL hash:', hash); // Debug log
if (hash) {
// Filter products directly using the hash as category
filterProducts(hash);
}
}
// Product Modal
function openProductModal(productId) {
const product = products[productId];
if (!product) return;
modalBody.innerHTML = `
<div class="modal-product">
<div class="modal-product-image">
<div class="placeholder-image">
<i class="fas fa-tshirt"></i>
</div>
</div>
<div class="modal-product-info">
<h2>${product.name}</h2>
<div class="modal-price">$${product.price.toFixed(2)}</div>
<p class="modal-description">${product.description}</p>
<div class="product-features">
<h4>Features:</h4>
<ul>
${product.features.map(feature => `<li>${feature}</li>`).join('')}
</ul>
</div>
<div class="product-options">
<div class="option-group">
<label>Size:</label>
<select class="size-select">
${product.sizes.map(size => `<option value="${size}">${size}</option>`).join('')}
</select>
</div>
<div class="option-group">
<label>Color:</label>
<select class="color-select">
${product.colors.map(color => `<option value="${color}">${color}</option>`).join('')}
</select>
</div>
<div class="option-group">
<label>Quantity:</label>
<div class="quantity-selector">
<button type="button" onclick="changeModalQuantity(-1)">-</button>
<input type="number" value="1" min="1" class="quantity-input">
<button type="button" onclick="changeModalQuantity(1)">+</button>
</div>
</div>
</div>
<button class="modal-add-to-cart" onclick="addToCartFromModal('${productId}')">
Add to Cart
</button>
</div>
</div>
`;
productModal.classList.add('open');
document.body.style.overflow = 'hidden';
}
function closeProductModal() {
productModal.classList.remove('open');
document.body.style.overflow = 'auto';
}
function changeModalQuantity(change) {
const quantityInput = document.querySelector('.quantity-input');
let currentValue = parseInt(quantityInput.value);
currentValue += change;
if (currentValue < 1) currentValue = 1;
quantityInput.value = currentValue;
}
function addToCartFromModal(productId) {
const product = products[productId];
const quantity = parseInt(document.querySelector('.quantity-input').value);
for (let i = 0; i < quantity; i++) {
addToCart(productId, product.name, product.price);
}
closeProductModal();
}
// Checkout
function checkout() {
if (cart.length === 0) {
showNotification('Your cart is empty!', 'error');
return;
}
// Simulate checkout process
showNotification('Redirecting to checkout...', 'success');
// In a real application, you would redirect to a payment processor
setTimeout(() => {
alert(`Thank you for your order! Total: $${cartTotalAmount.toFixed(2)}`);
cart = [];
updateCartDisplay();
toggleCart();
}, 2000);
}
// Notification System
function showNotification(message, type = 'success') {
const notification = document.createElement('div');
notification.className = `notification ${type}`;
notification.textContent = message;
// Add styles
notification.style.cssText = `
position: fixed;
top: 100px;
right: 20px;
background: ${type === 'success' ? '#27ae60' : '#e74c3c'};
color: white;
padding: 1rem 1.5rem;
border-radius: 8px;
box-shadow: 0 5px 15px rgba(0,0,0,0.2);
z-index: 1004;
transform: translateX(400px);
transition: transform 0.3s ease;
`;
document.body.appendChild(notification);
// Animate in
setTimeout(() => {
notification.style.transform = 'translateX(0)';
}, 100);
// Remove after 3 seconds
setTimeout(() => {
notification.style.transform = 'translateX(400px)';
setTimeout(() => {
document.body.removeChild(notification);
}, 300);
}, 3000);
}
// Contact Form
document.addEventListener('DOMContentLoaded', function() {
const contactForm = document.querySelector('.contact-form');
if (contactForm) {
contactForm.addEventListener('submit', function(e) {
e.preventDefault();
// Get form data
const formData = new FormData(this);
const name = this.querySelector('input[type="text"]').value;
const email = this.querySelector('input[type="email"]').value;
const message = this.querySelector('textarea').value;
// Simulate form submission
showNotification('Message sent successfully! We\'ll get back to you soon.', 'success');
// Reset form
this.reset();
});
}
});
// Close modal when clicking outside
productModal.addEventListener('click', function(e) {
if (e.target === productModal) {
closeProductModal();
}
});
// Close cart when clicking outside
document.addEventListener('click', function(e) {
if (!cartSidebar.contains(e.target) && !e.target.closest('.cart-btn')) {
if (cartSidebar.classList.contains('open')) {
toggleCart();
}
}
});
// Keyboard navigation
document.addEventListener('keydown', function(e) {
if (e.key === 'Escape') {
if (productModal.classList.contains('open')) {
closeProductModal();
}
if (cartSidebar.classList.contains('open')) {
toggleCart();
}
}
});
// Listen for hash changes (when users navigate to category URLs)
window.addEventListener('hashchange', function() {
handleCategoryFromURL();
});
// Search functionality
function toggleSearch() {
const searchBar = document.getElementById('search-bar');
searchBar.classList.toggle('active');
if (searchBar.classList.contains('active')) {
document.getElementById('search-input').focus();
}
}
function initializeSearch() {
const searchInput = document.getElementById('search-input');
if (!searchInput) return;
searchInput.addEventListener('input', function(e) {
const searchTerm = e.target.value.toLowerCase();
const productCards = document.querySelectorAll('.product-card');
productCards.forEach(card => {
const productName = card.querySelector('.product-name').textContent.toLowerCase();
const productDescription = card.querySelector('.product-description').textContent.toLowerCase();
if (productName.includes(searchTerm) || productDescription.includes(searchTerm)) {
card.style.display = 'block';
} else {
card.style.display = 'none';
}
});
});
// Search submit functionality
const searchSubmit = document.querySelector('.search-submit');
if (searchSubmit) {
searchSubmit.addEventListener('click', function() {
const searchTerm = searchInput.value.toLowerCase();
if (searchTerm.trim()) {
// Perform search
console.log('Searching for:', searchTerm);
showNotification(`Searching for: ${searchTerm}`, 'success');
}
});
}
}
// Lazy loading for images (when you add real images)
function initializeLazyLoading() {
const imageObserver = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
img.src = img.dataset.src;
img.classList.remove('lazy');
observer.unobserve(img);
}
});
});
document.querySelectorAll('img[data-src]').forEach(img => {
imageObserver.observe(img);
});
}
// Performance optimization
function debounce(func, wait) {
let timeout;
return function executedFunction(...args) {
const later = () => {
clearTimeout(timeout);
func(...args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}
// Scroll to top button
function initializeScrollToTop() {
const scrollButton = document.createElement('button');
scrollButton.innerHTML = '<i class="fas fa-arrow-up"></i>';
scrollButton.className = 'scroll-to-top';
scrollButton.style.cssText = `
position: fixed;
bottom: 20px;
right: 20px;
width: 50px;
height: 50px;
border-radius: 50%;
background: #3498db;
color: white;
border: none;
cursor: pointer;
display: none;
z-index: 1000;
transition: all 0.3s ease;
`;
document.body.appendChild(scrollButton);
window.addEventListener('scroll', debounce(() => {
if (window.pageYOffset > 300) {
scrollButton.style.display = 'block';
} else {
scrollButton.style.display = 'none';
}
}, 100));
scrollButton.addEventListener('click', () => {
window.scrollTo({
top: 0,
behavior: 'smooth'
});
});
}
// FAQ Functionality
function initializeFAQ() {
const faqItems = document.querySelectorAll('.faq-item');
faqItems.forEach(item => {
const question = item.querySelector('.faq-question');
question.addEventListener('click', () => {
const isActive = item.classList.contains('active');
// Close all FAQ items
faqItems.forEach(faq => faq.classList.remove('active'));
// Open clicked item if it wasn't active
if (!isActive) {
item.classList.add('active');
}
});
});
}
// Newsletter Functionality
function initializeNewsletter() {
const newsletterForm = document.getElementById('newsletter-form');
if (!newsletterForm) return;
newsletterForm.addEventListener('submit', function(e) {
e.preventDefault();
const email = this.querySelector('input[type="email"]').value;
// Simulate newsletter subscription
showNotification('Thank you for subscribing to our newsletter!', 'success');
this.reset();
});
}
// Contact Form Functionality
function initializeContactForm() {
const contactForm = document.getElementById('contact-form');
if (!contactForm) return;
contactForm.addEventListener('submit', function(e) {
e.preventDefault();
// Get form data
const formData = new FormData(this);
const name = this.querySelector('#name').value;
const email = this.querySelector('#email').value;
const subject = this.querySelector('#subject').value;
const message = this.querySelector('#message').value;
// Simulate form submission
showNotification('Message sent successfully! We\'ll get back to you soon.', 'success');
// Reset form
this.reset();
});
}
// Product Sorting
function sortProducts() {
const sortSelect = document.getElementById('sort-select');
const productsGrid = document.getElementById('products-grid');
const productCards = Array.from(productsGrid.querySelectorAll('.product-card'));
const sortBy = sortSelect.value;
productCards.sort((a, b) => {
const priceA = parseFloat(a.dataset.price);
const priceB = parseFloat(b.dataset.price);
const nameA = a.dataset.name.toLowerCase();
const nameB = b.dataset.name.toLowerCase();
switch(sortBy) {
case 'price-low':
return priceA - priceB;
case 'price-high':
return priceB - priceA;
case 'name':
return nameA.localeCompare(nameB);
default:
return 0;
}
});
// Reorder products in the grid
productCards.forEach(card => {
productsGrid.appendChild(card);
});
}
// Initialize additional features
document.addEventListener('DOMContentLoaded', function() {
initializeScrollToTop();
});