0% found this document useful (0 votes)
11 views6 pages

Category JS

The document is a JavaScript code that initializes a web application with smooth scrolling, user authentication, and dynamic item rendering based on category data fetched from an API. It includes functionalities for adding items to a cart, displaying a user's profile photo, and implementing a search feature to filter items. Additionally, it features animations for adding items to the cart and a responsive design for the user interface.

Uploaded by

lysdragon224
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views6 pages

Category JS

The document is a JavaScript code that initializes a web application with smooth scrolling, user authentication, and dynamic item rendering based on category data fetched from an API. It includes functionalities for adding items to a cart, displaying a user's profile photo, and implementing a search feature to filter items. Additionally, it features animations for adding items to the cart and a responsive design for the user interface.

Uploaded by

lysdragon224
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 6

import { auth, db } from './firebase.

js'; // Ensure this is correctly imported


import { doc, updateDoc, arrayUnion } from "firebase/firestore"; // Import
Firestore functions
import Lenis from '@studio-freight/lenis';
import { addToCart } from './cart.js';

// Initialize Lenis smooth scrolling


const lenis = new Lenis({
duration: 0.5, // Smooth scroll duration (in seconds)
easing: (t) => Math.min(1, 1.001 - Math.pow(2, -10 * t)), // Custom easing
direction: 'vertical', // Scroll direction
smooth: true, // Enable smooth scrolling
smoothTouch: false, // Disable smooth scrolling for touch devices
});

// RAF for smooth scrolling


function raf(time) {
lenis.raf(time);
requestAnimationFrame(raf);
}
requestAnimationFrame(raf);

let lastScrollPosition = 0; // Track the last scroll position


const searchBar = document.querySelector('.search-container'); // Reference the
search bar container

// Function to handle scroll events


function handleScroll() {
const currentScrollPosition = window.scrollY;
if (currentScrollPosition > lastScrollPosition) {
// Scrolling down
searchBar.style.transform = 'translateY(-100%)'; // Hide search bar
} else {
// Scrolling up
searchBar.style.transform = 'translateY(0)'; // Show search bar
}
lastScrollPosition = currentScrollPosition; // Update last scroll position
}

// Add event listener for scroll events


window.addEventListener('scroll', handleScroll);

const API_BASE_URL = import.meta.env.VITE_API_URL; // Replace with your API base


URL

// Dynamically set the user's profile photo


auth.onAuthStateChanged(async (user) => {
const profilePhoto = document.getElementById('profile-photo');
if (user && user.photoURL) {
profilePhoto.src = user.photoURL; // Use the logged-in user's profile photo
URL
} else {
profilePhoto.src = '/src/assets/default-avatar.png'; // Use a default
avatar if none exists
}
});

// Utility function to fetch data from API


function getCategoryFromURL() {
const urlParams = new URLSearchParams(window.location.search); // Extract query
params
const category = urlParams.get('category'); // Get the 'category' parameter
return category || 'default'; // Default category fallback
}

// Function to fetch category data


async function fetchCategoryData(category) {
console.log(category);
try {
const response = await fetch(`${API_BASE_URL}/${category}`);
if (!response.ok) {
throw new Error(`Error fetching category data: ${response.statusText}`);
}
return await response.json();
} catch (error) {
console.error(error);
return [];
}
}

// Function to render items dynamically


function renderItems(items) {
const itemsContainer = document.getElementById('items-container');
if (!itemsContainer) {
console.error('items-container not found in the DOM');
return;
}
itemsContainer.innerHTML = ''; // Clear any existing content
if (items.length === 0) {
itemsContainer.innerHTML = `<p>No items found for this category.</p>`;
return;
}
items.forEach(item => {
const itemElement = document.createElement('div');
itemElement.classList.add('item-card');
itemElement.innerHTML = `
<img src="${item['Image URL']}" alt="${item.Name}" class="item-image"
loading="lazy">
<h3 class="item-name">${item.Name}</h3>
<p class="item-price">${item.Price}</p>
<button class="add-to-cart-btn">Add to Cart</button>
`;

// Add event listener for "Add to Cart" button


const addToCartButton = itemElement.querySelector('.add-to-cart-btn');
addToCartButton.addEventListener('click', () => {
addToCart(item); // Call the addToCart function with the item
});

itemsContainer.appendChild(itemElement);
});
}

function filterItems(items, query) {


query = query.toLowerCase();
return items.filter((item) =>
item.Name.toLowerCase().includes(query) ||
item.Price.toLowerCase().includes(query)
);
}

// Function to initialize the page


async function initializePage() {
const category = new URLSearchParams(window.location.search).get("category");
const dynamicTitle = document.getElementById("dynamic-title");
if (!dynamicTitle) {
console.error("dynamic-title element not found in the DOM");
return;
}
// Set the category title
dynamicTitle.textContent = category.charAt(0).toUpperCase() +
category.slice(1);
// Fetch items and render them
const items = await fetchCategoryData(category);
renderItems(items);
// Add search bar functionality
const searchBar = document.getElementById("search-bar");
if (!searchBar) {
console.error("search-bar not found in the DOM");
return;
}
searchBar.addEventListener("input", (event) => {
const query = event.target.value;
const filteredItems = filterItems(items, query);
renderItems(filteredItems);
});
}

// Ensure DOM is fully loaded before initializing


document.addEventListener("DOMContentLoaded", initializePage);

// Add cart button functionality


const cartButton = document.querySelector('.header-right button');
if (cartButton) {
cartButton.addEventListener('click', () => {
// Add your cart functionality here
console.log('Cart button clicked');
});
}

// Add profile photo click functionality


const profilePhoto = document.getElementById('profile-photo');
if (profilePhoto) {
profilePhoto.addEventListener('click', () => {
// Add your profile functionality here
console.log('Profile photo clicked');
});
}

// Add to cart function


// async function addToCart(item) {
// try {
// const user = auth.currentUser;
// if (!user) {
// console.error('No user logged in');
// return;
// }
// // Reference to the user's document in Firestore
// const userDocRef = doc(db, 'users', user.uid);

// // Update the user's cart with the new item


// await updateDoc(userDocRef, {
// cart: arrayUnion(item) // Use arrayUnion to add the item to the cart
array
// });

// console.log('Item added to cart:', item);

// // Trigger the animation


// animateToCart(item['Image URL']);
// } catch (error) {
// console.error('Error adding to cart:', error);
// }
// }

// Function to animate the product image sliding into the cart


function animateToCart(imageUrl) {
// Create a clone of the product image
const flyingImage = document.createElement('img');
flyingImage.src = imageUrl;
flyingImage.style.position = 'fixed';
flyingImage.style.width = '50px'; // Initial size
flyingImage.style.height = 'auto';
flyingImage.style.zIndex = '1001'; // Ensure it's above other elements
flyingImage.style.pointerEvents = 'none'; // Make it non-interactive
flyingImage.style.borderRadius = '10px'; // Rounded corners for aesthetics

// Position the flying image at the current mouse position


const rect = document.querySelector('.button-
container').getBoundingClientRect();
flyingImage.style.left = `${rect.left + rect.width / 2}px`;
flyingImage.style.top = `${rect.top + rect.height / 2}px`;

// Append the flying image to the body


document.body.appendChild(flyingImage);

// Get the cart icon position


const cartIcon = document.querySelector('.cart-icon');
const cartRect = cartIcon.getBoundingClientRect();

// Animate the flying image to the cart icon


flyingImage.animate(
[
{
left: `${rect.left + rect.width / 2}px`,
top: `${rect.top + rect.height / 2}px`,
transform: 'scale(1)',
opacity: 1,
},
{
left: `${cartRect.left + cartRect.width / 2}px`,
top: `${cartRect.top + cartRect.height / 2}px`,
transform: 'scale(0.5)', // Shrink as it moves
opacity: 0, // Fade out
},
],
{
duration: 800, // Animation duration in milliseconds
easing: 'ease-in-out', // Smooth easing
fill: 'forwards', // Keep the final state
}
);

// Remove the flying image after the animation ends


setTimeout(() => {
flyingImage.remove();
}, 800); // Match the animation duration
}

// Create button container


function createButtonContainer(event, item) {
// Remove any existing button container
const existingContainer = document.querySelector('.button-container');
if (existingContainer) {
existingContainer.classList.add('removing');
existingContainer.addEventListener('animationend', () =>
existingContainer.remove());
}

// Create new container


const container = document.createElement('div');
container.className = 'button-container';

// Position the container at the click location


container.style.left = `${event.clientX}px`;
container.style.top = `${event.clientY}px`;

// Add buttons with new close button structure


container.innerHTML = `
<button class="add-to-cart">
<img src="/src/assets/cartIcon.png" alt="Add to Cart" class="cart-icon-
popup">
</button>
<button class="close">
<span class="X"></span>
<span class="Y"></span>
</button>
`;

// Add event listeners


container.querySelector('.add-to-cart').addEventListener('click', () => {
addToCart(item);
container.classList.add('removing');
container.addEventListener('animationend', () => container.remove());
});

container.querySelector('.close').addEventListener('click', () => {
container.classList.add('removing');
container.addEventListener('animationend', () => container.remove());
});

// Add click outside handler


setTimeout(() => {
document.addEventListener('click', function clickOutsideHandler(e) {
if (!container.contains(e.target)) {
container.classList.add('removing');
container.addEventListener('animationend', () => {
container.remove();
document.removeEventListener('click', clickOutsideHandler);
});
}
});
}, 0);

// Append the container to the body


document.body.appendChild(container);

// Hide the button container on scroll


const handleScroll = () => {
container.classList.add('removing');
container.addEventListener('animationend', () => container.remove());
window.removeEventListener('scroll', handleScroll); // Remove listener
after hiding
};

window.addEventListener('scroll', handleScroll);

// Automatically remove the container after 5 seconds


setTimeout(() => {
if (container && !container.classList.contains('removing')) {
container.classList.add('removing');
container.addEventListener('animationend', () => container.remove());
}
}, 5000); // 5 seconds timeout
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy