// Function to Show Alert Messages
function showAlert(message, duration = 1000) {
customAlert.textContent = message;
customAlert.style.display = 'block';
setTimeout(() => {
customAlert.style.display = 'none';
}, duration);
}
// Function to Add Product to Cart
function addToCart(product) {
cart.push(product);
updateCartCount();
showAlert(${product.name} has been added to your cart!);
}
// Function to Update Cart Count Display
function updateCartCount() {
cartCount++;
cartCountElement.textContent = cartCount;
}
// Function to Fetch Products from Server
async function fetchProducts() {
try {
const response = await fetch('/fetch_products.php', {
method: 'GET',
headers: {
'Accept': 'application/json',
}
// Removed mode: 'cors' as it's unnecessary for same-origin requests
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const products = await response.json();
return products;
// Function to Create HTML for a Product Card
function createProductCard(product) {
// Define a default image path for products without images
const defaultImagePath = '/static/images/loveessential_ke-08092024-0007.jpeg'; // Ensure this image exists on your server
} catch (error) {
showAlert('Failed to load products. Please try again later.', 2000);
}
}
// Function to Attach Event Listeners to "Add to Cart" Buttons
function attachAddToCartListeners() {
const addToCartButtons = document.querySelectorAll('.add-to-cart');
addToCartButtons.forEach(button => {
button.addEventListener('click', () => {
const productId = button.getAttribute('data-product-id');
const product = products.find(p => p.id == productId);
if (product) {
addToCart(product);
} else {
showAlert('Product not found.', 2000);
}
});
});
}
// Function to Send Cart Details to Local Storage and Redirect to Cart Page
function sendCartDetails() {
const cartJSON = JSON.stringify(cart);
localStorage.setItem('cart', cartJSON);
window.location.href = '/cart';
}
// Event Listener for Cart Icon Click
const cartIcon = document.getElementById('cartIcon');
if (cartIcon) {
cartIcon.addEventListener('click', function(e) {
e.preventDefault();
sendCartDetails();
});
} else {
console.warn('Cart icon not found. Please check the selector.');
}
// Newsletter Form Handling with Fixed Reference
const newsletterForm = document.querySelector('.newsletter form');
if (newsletterForm) {
newsletterForm.addEventListener('submit', (e) => {
e.preventDefault();
const emailInput = newsletterForm.querySelector('input[type="email"]');
if (emailInput.value.includes('@') && emailInput.value.includes('.')) {
showAlert('Thank you for subscribing to our newsletter!', 2000);
emailInput.value = '';
} else {
showAlert('Please enter a valid email address.', 2000);
}
});
} else {
console.warn('Newsletter form not found. Please check the selector.');
}
// Function to Populate Products on Page Load
populateProducts();
// Cookie Consent Functionality
function setCookie(name, value, days) {
const expires = new Date(Date.now() + days * 24 * 60 * 60 * 1000).toUTCString();
document.cookie = name + '=' + encodeURIComponent(value) + '; expires=' + expires + '; path=/';
}
function getCookie(name) {
return document.cookie.split('; ').reduce((r, v) => {
const parts = v.split('=');
return parts[0] === name ? decodeURIComponent(parts[1]) : r;
}, '');
}
if (cookieBanner && acceptCookiesButton) {
if (!getCookie('cookiesAccepted')) {
cookieBanner.style.display = 'block';
}
acceptCookiesButton.addEventListener('click', () => {
setCookie('cookiesAccepted', 'true', 365);
cookieBanner.style.display = 'none';
});
} else {
console.warn('Cookie banner or accept button not found. Please check the selectors.');
}
// Function for Tab Navigation (Assuming Tabs Are Present)
function setupTabNavigation() {
const tabs = document.querySelectorAll('.tab');
if (tabs.length === 0) return;
tabs.forEach(tab => {
tab.addEventListener('click', function() {
// Remove 'active' class from all tabs
tabs.forEach(t => t.classList.remove('active'));
// Add 'active' class to the clicked tab
this.classList.add('active');
// Hide all tab contents
const tabContents = document.querySelectorAll('.tab-content');
tabContents.forEach(content => content.classList.remove('active'));
// Show the corresponding tab content
const targetTabContentId = `${this.getAttribute('data-tab')}Tab`;
const targetTabContent = document.getElementById(targetTabContentId);
if (targetTabContent) {
targetTabContent.classList.add('active');
}
});
});
}
Certainly! Below is a comprehensive JavaScript implementation tailored to your provided HTML page. This script covers the following functionalities:
Cart Management:
Add to Cart: Adds the selected product with the specified quantity to the cart.
Cart Count: Updates and displays the number of items in the cart.
Persist Cart Data: Stores the cart data in localStorage to maintain state across sessions.
Cart Icon Click: Redirects users to the cart page.
Quantity Controls:
Increase/Decrease Buttons: Allows users to adjust the quantity of the product they wish to add to the cart.
Image and Video Handling:
Thumbnail Click: Changes the main product image or displays the product video.
Custom Alerts:
Notification System: Displays success or error messages to users.
Newsletter Subscription:
Form Handling: Validates and processes newsletter subscriptions.
Cookie Consent:
Banner Display: Manages the display and acceptance of cookie consent.
Related Products (Optional):
Dynamic Loading: Fetches and displays related products (assuming you have an endpoint to fetch them).
Here's the complete JavaScript code integrated into your HTML. Place this <script> section just before the closing </body> tag, replacing your existing <script> block.
<!DOCTYPE html>
<html lang="en">
<head>
<!-- [Your existing head content] -->
</head>
<body>
<!-- [Your existing body content] -->
<!-- Custom JavaScript -->
<script>
document.addEventListener('DOMContentLoaded', () => {
// =========================
// Global Variables
// =========================
let cart = JSON.parse(localStorage.getItem('cart')) || [];
const cartCountElement = document.querySelector('.cart-count');
const customAlert = document.getElementById('customAlert');
const addToCartButton = document.querySelector('.add-to-cart');
const decreaseButton = document.getElementById('decrease-quantity');
const increaseButton = document.getElementById('increase-quantity');
const quantityInput = document.getElementById('quantity');
const cartIcon = document.getElementById('cartIcon');
const newsletterForm = document.querySelector('.newsletter form');
const cookieBanner = document.getElementById('cookie-banner');
const acceptCookiesButton = document.getElementById('accept-cookies');
// =========================
// Functions
// =========================
// Function to Show Alert Messages
function showAlert(message, type = 'success', duration = 3000) {
customAlert.textContent = message;
customAlert.className = `custom-alert ${type}`;
customAlert.style.display = 'block';
setTimeout(() => {
customAlert.style.display = 'none';
}, duration);
}
// Function to Update Cart Count Display
function updateCartCount() {
const totalCount = cart.reduce((acc, item) => acc + item.quantity, 0);
cartCountElement.textContent = totalCount;
}
// Function to Save Cart to Local Storage
function saveCart() {
localStorage.setItem('cart', JSON.stringify(cart));
}
// Function to Add Product to Cart
function addToCart(product) {
const existingProductIndex = cart.findIndex(item => item.id === product.id);
if (existingProductIndex >= 0) {
// If product already in cart, update quantity
cart[existingProductIndex].quantity += product.quantity;
} else {
// Add new product to cart
cart.push(product);
}
saveCart();
updateCartCount();
showAlert(`${product.name} has been added to your cart!`, 'success');
}
// Function to Validate Email
function isValidEmail(email) {
// Simple email regex validation
const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return re.test(String(email).toLowerCase());
}
// Function to Set Cookie
function setCookie(name, value, days) {
const expires = new Date(Date.now() + days * 864e5).toUTCString();
document.cookie = name + '=' + encodeURIComponent(value) + '; expires=' + expires + '; path=/';
}
// Function to Get Cookie
function getCookie(name) {
return document.cookie.split('; ').reduce((r, v) => {
const parts = v.split('=');
return parts[0] === name ? decodeURIComponent(parts[1]) : r;
}, '');
}
// =========================
// Event Listeners
// =========================
// Initialize Cart Count on Page Load
updateCartCount();
// Event Listener for Add to Cart Button
if (addToCartButton) {
addToCartButton.addEventListener('click', () => {
const productId = addToCartButton.getAttribute('data-product-id');
const productName = document.querySelector('.product-title').textContent.trim();
const productPriceText = document.querySelector('.product-price').textContent.trim();
const productPrice = parseFloat(productPriceText.replace(' Ksh', ''));
const productImage = document.getElementById('main-image').src;
const quantity = parseInt(quantityInput.value) || 1;
if (quantity < 1) {
showAlert('Quantity must be at least 1.', 'error');
return;
}
const product = {
id: productId,
name: productName,
price: productPrice,
image: productImage,
quantity: quantity
};
addToCart(product);
});
}
// Event Listeners for Quantity Buttons
if (decreaseButton && quantityInput) {
decreaseButton.addEventListener('click', () => {
let currentValue = parseInt(quantityInput.value) || 1;
if (currentValue > 1) {
quantityInput.value = currentValue - 1;
}
});
}
if (increaseButton && quantityInput) {
increaseButton.addEventListener('click', () => {
let currentValue = parseInt(quantityInput.value) || 1;
quantityInput.value = currentValue + 1;
});
}
// Event Listener for Cart Icon Click
if (cartIcon) {
cartIcon.addEventListener('click', (e) => {
e.preventDefault();
window.location.href = '/cart';
});
}
// Event Listener for Newsletter Form Submission
if (newsletterForm) {
newsletterForm.addEventListener('submit', (e) => {
e.preventDefault();
const emailInput = newsletterForm.querySelector('input[type="email"]');
const email = emailInput.value.trim();
if (isValidEmail(email)) {
// Here you would typically send the email to your server
showAlert('Thank you for subscribing to our newsletter!', 'success');
emailInput.value = '';
} else {
showAlert('Please enter a valid email address.', 'error');
}
});
}
// Cookie Consent Handling
if (cookieBanner && acceptCookiesButton) {
if (!getCookie('cookiesAccepted')) {
cookieBanner.style.display = 'block';
}
acceptCookiesButton.addEventListener('click', () => {
setCookie('cookiesAccepted', 'true', 365);
cookieBanner.style.display = 'none';
showAlert('Cookies have been accepted.', 'success');
});
}
// Optional: Handling Related Products (Assuming an endpoint exists)
/*
async function fetchRelatedProducts() {
try {
const response = await fetch('/fetch_related_products.php?category={{category}}', {
method: 'GET',
headers: {
'Accept': 'application/json',
}
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const relatedProducts = await response.json();
const relatedProductsContainer = document.querySelector('.related-products .product-grid');
if (relatedProductsContainer) {
relatedProductsContainer.innerHTML = relatedProducts.map(createProductCard).join('');
}
attachAddToCartListeners();
} catch (error) {
console.error('Error fetching related products:', error);
showAlert('Failed to load related products.', 'error');
}
}
// Call fetchRelatedProducts if needed
fetchRelatedProducts();
*/
// =========================
// Utility Functions
// =========================
// You can add more utility functions here as needed
});
// =========================
// Existing Functions (Retained)
// =========================
function showVideo() {
document.getElementById('main-image').style.display = 'none';
document.getElementById('youtube-video').style.display = 'block';
}
function changeMainImage(src) {
document.getElementById('main-image').src = src;
document.getElementById('main-image').style.display = 'block';
document.getElementById('youtube-video').style.display = 'none';
}
</script>
<!-- [Your remaining body content, if any] -->
</body>
</html>
Explanation of the JavaScript Code:
Cart Management:
Initialization: Retrieves the existing cart from localStorage or initializes an empty array if none exists.
updateCartCount Function: Calculates the total number of items in the cart and updates the cart count displayed next to the cart icon.
saveCart Function: Saves the current state of the cart to localStorage to ensure persistence across page reloads.
addToCart Function: Handles adding a product to the cart. If the product already exists in the cart, it updates the quantity; otherwise, it adds the new product.
Quantity Controls:
Decrease Quantity: Decrements the quantity input, ensuring it doesn't go below 1.
Increase Quantity: Increments the quantity input.
Add to Cart Button:
Gathers necessary product details such as id, name, price, image, and quantity.
Validates the quantity to ensure it's at least 1.
Calls the addToCart function to add the product to the cart.
Cart Icon Click:
Redirects the user to the /cart page when the cart icon is clicked.
Custom Alert System:
showAlert Function: Displays a custom alert with a message, type (success or error), and duration. The styling of the alert can be customized via CSS based on the type.
Newsletter Subscription:
Validates the email format using a regular expression.
Displays a success or error message based on the validation.
Note: You'll need to implement the server-side logic to handle the actual subscription process.
Cookie Consent:
Displays the cookie consent banner if the user hasn't accepted cookies yet.
Sets a cookie when the user accepts to prevent the banner from showing again for 365 days.
Displays a success alert upon acceptance.
Additional Recommendations:
Custom Alerts Styling:
Ensure you style the .custom-alert, .custom-alert.success, and .custom-alert.error classes in your CSS to match your website's design.
Handling Related Products:
If you decide to implement the related products section, ensure that your backend can serve related products based on categories or other criteria. Update the fetch URL and response handling as needed.
Security Considerations:
Always sanitize and validate data both on the client and server sides to prevent security vulnerabilities such as XSS or injection attacks.
Accessibility:
Ensure that all interactive elements are accessible via keyboard and are properly labeled for screen readers to enhance usability for all users.
Performance Optimization:
Consider debouncing rapid clicks on the "Add to Cart" button to prevent accidental multiple additions. Additionally, lazy-load images and optimize assets to improve page load times.
Final Notes:
This implementation provides a robust foundation for e-commerce functionalities on your product page. Depending on your specific requirements and backend setup, you might need to adjust certain parts of the code, especially the parts interacting with server endpoints. Always test thoroughly across different browsers and devices to ensure a seamless user experience.
If you have any specific requirements or encounter issues while integrating this script, feel free to ask for further assistance!