thulieu's picture
Upload 63 files
53b07b2 verified
/*=============== SEARCH ===============*/
const searchButton = document.getElementById("search-button"),
searchClose = document.getElementById("search-close"),
searchContent = document.getElementById("search-content");
/*===== SEARCH SHOW =====*/
/* Validate if constant exists */
if (searchButton) {
searchButton.addEventListener("click", () => {
searchContent.classList.add("show-search");
});
}
/*===== SEARCH HIDDEN =====*/
/* Validate if constant exists */
if (searchClose) {
searchClose.addEventListener("click", () => {
searchContent.classList.remove("show-search");
});
}
/*=============== SHOPPING BAG ===============*/
const bagButton = document.getElementById("bag-button"),
bagClose = document.getElementById("bag-close"),
bagContent = document.getElementById("bag-content");
/*===== CART SHOW =====*/
/* Validate if constant exists */
if (bagButton) {
bagButton.addEventListener("click", () => {
bagContent.classList.add("show-bag");
});
}
/*===== CART HIDDEN =====*/
/* Validate if constant exists */
if (bagClose) {
bagClose.addEventListener("click", () => {
bagContent.classList.remove("show-bag");
});
}
/*=============== LOGIN ===============*/
/*=============== LOGIN & USER MENU ===============*/
const loginButton = document.getElementById("login-button"),
loginClose = document.getElementById("login-close"),
loginContent = document.getElementById("login-content"),
userMenuClose = document.getElementById("user-menu-close"),
userMenuContent = document.getElementById("user-menu-content");
/*===== HANDLE LOGIN BUTTON CLICK =====*/
if (loginButton) {
loginButton.addEventListener("click", () => {
// Kiểm tra trạng thái đăng nhập
const isLoggedIn = localStorage.getItem("isLoggedIn") === "true";
if (isLoggedIn) {
// Đã đăng nhập -> hiển thị user menu
showUserMenu();
} else {
// Chưa đăng nhập -> hiển thị form đăng nhập
loginContent.classList.add("show-login");
}
});
}
/*===== LOGIN FORM HIDDEN =====*/
if (loginClose) {
loginClose.addEventListener("click", () => {
loginContent.classList.remove("show-login");
});
}
/*===== USER MENU HIDDEN =====*/
if (userMenuClose) {
userMenuClose.addEventListener("click", () => {
userMenuContent.classList.remove("show-user-menu");
});
}
/*=============== LOGIN FORM HANDLER ===============*/
document.addEventListener("DOMContentLoaded", function () {
const loginForm = document.querySelector(".login__form");
if (loginForm) {
loginForm.addEventListener("submit", handleLogin);
}
});
function handleLogin(event) {
// Ngăn form submit mặc định (reload trang)
event.preventDefault();
// Lấy giá trị từ input
const emailInput = document.getElementById("login-email");
const passwordInput = document.getElementById("login-pass");
const email = emailInput.value.trim();
const password = passwordInput.value.trim();
// Kiểm tra thông tin đăng nhập
validateLogin(email, password);
}
function validateLogin(email, password) {
// Thông tin đăng nhập đúng
const VALID_EMAIL = "dothulieu12@gmail.com";
const VALID_PASSWORD = "lieu123";
// Kiểm tra email và password có trống không
if (!email || !password) {
showLoginMessage("Vui lòng nhập đầy đủ email và mật khẩu!", "error");
return;
}
// Kiểm tra thông tin đăng nhập
if (email === VALID_EMAIL && password === VALID_PASSWORD) {
showLoginMessage(
"Đăng nhập thành công! Chào mừng bạn đến với ThuLieu Store!",
"success"
);
// Đóng modal sau khi đăng nhập thành công
setTimeout(() => {
closeLoginModal();
clearLoginForm();
}, 2000);
} else {
showLoginMessage(
"Email hoặc mật khẩu không đúng. Vui lòng thử lại!",
"error"
);
}
}
function showLoginMessage(message, type) {
// Tạo element thông báo
const messageDiv = document.createElement("div");
messageDiv.className = `login__message login__message--${type}`;
messageDiv.textContent = message;
// Tìm form để chèn thông báo
const loginForm = document.querySelector(".login__form");
const loginTitle = document.querySelector(".login__title");
// Xóa thông báo cũ nếu có
const existingMessage = loginForm.querySelector(".login__message");
if (existingMessage) {
existingMessage.remove();
}
// Chèn thông báo sau title
loginTitle.insertAdjacentElement("afterend", messageDiv);
// Tự động ẩn thông báo sau 5 giây
setTimeout(() => {
if (messageDiv.parentNode) {
messageDiv.remove();
}
}, 5000);
}
function closeLoginModal() {
const loginContent = document.getElementById("login-content");
if (loginContent) {
loginContent.classList.remove("show-login");
}
}
function clearLoginForm() {
const emailInput = document.getElementById("login-email");
const passwordInput = document.getElementById("login-pass");
if (emailInput) emailInput.value = "";
if (passwordInput) passwordInput.value = "";
// Xóa thông báo
const messageDiv = document.querySelector(".login__message");
if (messageDiv) {
messageDiv.remove();
}
}
function validateLogin(email, password) {
const VALID_EMAIL = "dothulieu12@gmail.com";
const VALID_PASSWORD = "lieu123";
// Hiển thị loading
showLoginMessage("Đang xử lý...", "loading");
// Giả lập thời gian xử lý
setTimeout(() => {
if (!email || !password) {
showLoginMessage("Vui lòng nhập đầy đủ email và mật khẩu!", "error");
return;
}
if (email === VALID_EMAIL && password === VALID_PASSWORD) {
// Lưu trạng thái đăng nhập
localStorage.setItem("isLoggedIn", "true");
localStorage.setItem("userEmail", email);
showLoginMessage(
"Đăng nhập thành công! Chào mừng bạn đến với ThuLieu Store!",
"success"
);
setTimeout(() => {
closeLoginModal();
clearLoginForm();
updateUIAfterLogin();
}, 2000);
} else {
showLoginMessage(
"Email hoặc mật khẩu không đúng. Vui lòng thử lại!",
"error"
);
}
}, 1000);
}
function updateUIAfterLogin() {
// Thay đổi icon đăng nhập thành icon user đã đăng nhập
const loginButton = document.getElementById("login-button");
if (loginButton) {
loginButton.classList.remove("ri-user-line");
loginButton.classList.add("ri-user-3-fill");
loginButton.title = "Thông tin tài khoản";
// Thêm class để đánh dấu đã đăng nhập
loginButton.classList.add("logged-in");
}
}
/*=============== ADD SHADOW HEADER ===============*/
const shadowHeader = () => {
const header = document.getElementById("header");
// When the scroll is greater than 50 viewport height, add the shadow-header class to the header tag
this.scrollY >= 50
? header.classList.add("shadow-header")
: header.classList.remove("shadow-header");
};
window.addEventListener("scroll", shadowHeader);
/*=============== HOME SWIPER ===============*/
let swiperHome = new Swiper(".home__swiper", {
loop: true,
spaceBetween: -24,
grabCursor: true,
slidesPerView: "auto",
centeredSlides: "auto",
autoplay: {
delay: 3000,
disableOnInteraction: false,
},
breakpoints: {
1220: {
spaceBetween: -32,
},
},
});
/*=============== FEATURED SWIPER ===============*/
// Khởi tạo swiper cho tất cả các category
document.addEventListener("DOMContentLoaded", function () {
// Tìm tất cả các swiper trong featured
const featuredSwipers = document.querySelectorAll(".featured__swiper");
featuredSwipers.forEach((swiperElement, index) => {
new Swiper(swiperElement, {
loop: true,
spaceBetween: 16,
grabCursor: true,
slidesPerView: "auto",
centeredSlides: "auto",
navigation: {
nextEl: swiperElement.querySelector(".swiper-button-next"),
prevEl: swiperElement.querySelector(".swiper-button-prev"),
},
breakpoints: {
1150: {
slidesPerView: 4,
centeredSlides: false,
},
},
// Thêm class unique cho mỗi swiper
on: {
init: function () {
swiperElement.classList.add(`featured-swiper-${index + 1}`);
},
},
});
});
});
/*=============== FEATURED ADD TO CART ===============*/
document.addEventListener("DOMContentLoaded", function () {
const addToCartButtons = document.querySelectorAll(".featured__card .button");
const clearCartButton = document.getElementById("clearCart");
const checkoutButton = document.getElementById("checkOut");
addToCartButtons.forEach((button) => {
button.addEventListener("click", addToCartHandler);
});
clearCartButton.addEventListener("click", clearCartHandler);
checkoutButton.addEventListener("click", checkoutHandler);
updateCartUI();
});
function addToCartHandler(event) {
const featuredCard = event.target.closest(".featured__card");
const productName = featuredCard.querySelector(".featured__title").innerText;
const productPrice =
parseFloat(
featuredCard.querySelector(".featured__discount").dataset.price
) || 0;
alert(`Đã thêm vào giỏ hàng: ${productName}`);
addToCart(productName, productPrice);
updateCartUI();
}
function addToCart(productName, productPrice) {
let cartItems = JSON.parse(localStorage.getItem("cartItems")) || [];
cartItems.push({ name: productName, price: productPrice });
localStorage.setItem("cartItems", JSON.stringify(cartItems));
}
function updateCartUI() {
const cartItemsContainer = document.getElementById("cartItemsContainer");
const cartItems = JSON.parse(localStorage.getItem("cartItems")) || [];
cartItemsContainer.innerHTML = "";
cartItems.forEach((item) => {
const cartItemElement = document.createElement("div");
cartItemElement.innerText = `${item.name} - ${item.price} VND`;
cartItemsContainer.appendChild(cartItemElement);
});
const totalAmount = calculateTotalAmount(cartItems);
displayTotalAmount(totalAmount);
}
function calculateTotalAmount(cartItems) {
return cartItems.reduce((total, item) => total + item.price, 0);
}
function displayTotalAmount(amount) {
let totalAmountContainer = document.getElementById("totalAmountContainer");
if (!totalAmountContainer) {
totalAmountContainer = document.createElement("div");
totalAmountContainer.id = "totalAmountContainer";
const bagForm = document.querySelector(".bag__form");
bagForm.appendChild(totalAmountContainer);
}
totalAmountContainer.innerText = `Tổng cộng: ${amount} VND`;
}
function clearCartHandler() {
localStorage.removeItem("cartItems");
updateCartUI();
}
function checkoutHandler() {
alert("Đã thanh toán thành công!");
resetCart();
updateCartUI();
}
function resetCart() {
localStorage.removeItem("cartItems");
}
/*=============== NEW SWIPER ===============*/
let swiperNew = new Swiper(".new__swiper", {
loop: false,
spaceBetween: 16,
slidesPerView: "auto",
breakpoints: {
1150: {
slidesPerView: 3,
},
},
});
/*=============== TESTIMONIAL SWIPER ===============*/
let swiperTestimonial = new Swiper(".testimonial__swiper", {
loop: true,
spaceBetween: 16,
grabCursor: true,
slidesPerView: "auto",
centeredSlides: "auto",
breakpoints: {
1150: {
slidesPerView: 3,
centeredSlides: false,
},
},
});
/*=============== SHOW SCROLL UP ===============*/
const scrollUp = () => {
const scrollUp = document.getElementById("scroll-up");
// When the scroll is higher than 350 viewport height, add the show-scroll class to the a tag with the scrollup class
this.scrollY >= 350
? scrollUp.classList.add("show-scroll")
: scrollUp.classList.remove("show-scroll");
};
window.addEventListener("scroll", scrollUp);
/*=============== SCROLL SECTIONS ACTIVE LINK ===============*/
const sections = document.querySelectorAll("section[id]");
const scrollActive = () => {
const scrollDown = window.scrollY;
sections.forEach((current) => {
const sectionHeight = current.offsetHeight,
sectionTop = current.offsetTop - 58,
sectionId = current.getAttribute("id"),
sectionsClass = document.querySelector(
".nav__menu a[href*=" + sectionId + "]"
);
if (scrollDown > sectionTop && scrollDown <= sectionTop + sectionHeight) {
sectionsClass.classList.add("active-link");
} else {
sectionsClass.classList.remove("active-link");
}
});
};
window.addEventListener("scroll", scrollActive);
/*=============== DARK LIGHT THEME ===============*/
const themeButton = document.getElementById("theme-button");
const darkTheme = "dark-theme";
const iconTheme = "ri-sun-line";
// Previously selected topic (if user selected)
const selectedTheme = localStorage.getItem("selected-theme");
const selectedIcon = localStorage.getItem("selected-icon");
// We obtain the current theme that the interface has by validating the dark-theme class
const getCurrentTheme = () =>
document.body.classList.contains(darkTheme) ? "dark" : "light";
const getCurrentIcon = () =>
themeButton.classList.contains(iconTheme) ? "ri-moon-line" : "ri-sun-line";
// We validate if the user previously chose a topic
if (selectedTheme) {
// If the validation is fulfilled, we ask what the issue was to know if we activated or deactivated the dark
document.body.classList[selectedTheme === "dark" ? "add" : "remove"](
darkTheme
);
themeButton.classList[selectedIcon === "ri-moon-line" ? "add" : "remove"](
iconTheme
);
}
// Activate / deactivate the theme manually with the button
themeButton.addEventListener("click", () => {
// Add or remove the dark / icon theme
document.body.classList.toggle(darkTheme);
themeButton.classList.toggle(iconTheme);
// We save the theme and the current icon that the user chose
localStorage.setItem("selected-theme", getCurrentTheme());
localStorage.setItem("selected-icon", getCurrentIcon());
});
/*=============== SCROLL REVEAL ANIMATION ===============*/
const sr = ScrollReveal({
origin: "top",
distance: "60px",
duration: 2500,
delay: 400,
});
sr.reveal(`.home__data, .new__container,
.join__data, .testimonial__container, .footer`);
sr.reveal(`.home__images`, { delay: 600 });
sr.reveal(`.services__card`, { interval: 100 });
sr.reveal(`.discount__data`, { origin: "left" });
sr.reveal(`.discount__images`, { origin: "right" });
// Thêm animation cho category headers
sr.reveal(`.featured__category-header`, {
interval: 200,
distance: "30px",
duration: 1000,
});
// Animation cho featured containers
sr.reveal(`.featured__container`, {
interval: 300,
delay: 200,
});
/*=============== OPEN DETAIL TAB ===============*/
function openDetailPage() {
// Đường dẫn tới trang detail.html
var detailPageURL = "product_detail.html";
// Mở tab mới
window.open(detailPageURL, "_blank");
}
/*================ CART ========================*/
/*=============== FEATURED ADD TO CART ===============*/
document.addEventListener("DOMContentLoaded", function () {
const addToCartButtons = document.querySelectorAll(".featured__card .button");
const clearCartButton = document.getElementById("clearCart");
const checkoutButton = document.getElementById("checkOut");
addToCartButtons.forEach((button) => {
button.addEventListener("click", addToCartHandler);
});
clearCartButton.addEventListener("click", clearCartHandler);
checkoutButton.addEventListener("click", checkoutHandler);
updateCartUI();
});
function addToCartHandler(event) {
const featuredCard = event.target.closest(".featured__card");
const productName = featuredCard.querySelector(".featured__title").innerText;
const productPrice =
parseFloat(
featuredCard.querySelector(".featured__discount").dataset.price
) || 0;
alert(`Đã thêm vào giỏ hàng: ${productName}`);
addToCart(productName, productPrice);
updateCartUI();
}
function addToCart(productName, productPrice) {
let cartItems = JSON.parse(localStorage.getItem("cartItems")) || [];
cartItems.push({ name: productName, price: productPrice });
localStorage.setItem("cartItems", JSON.stringify(cartItems));
}
function updateCartUI() {
const cartItemsContainer = document.getElementById("cartItemsContainer");
const cartItems = JSON.parse(localStorage.getItem("cartItems")) || [];
cartItemsContainer.innerHTML = "";
cartItems.forEach((item) => {
const cartItemElement = document.createElement("div");
cartItemElement.innerText = `${item.name} - ${item.price} VND`;
cartItemsContainer.appendChild(cartItemElement);
});
const totalAmount = calculateTotalAmount(cartItems);
displayTotalAmount(totalAmount);
}
function calculateTotalAmount(cartItems) {
return cartItems.reduce((total, item) => total + item.price, 0);
}
function displayTotalAmount(amount) {
let totalAmountContainer = document.getElementById("totalAmountContainer");
if (!totalAmountContainer) {
totalAmountContainer = document.createElement("div");
totalAmountContainer.id = "totalAmountContainer";
const bagForm = document.querySelector(".bag__form");
bagForm.appendChild(totalAmountContainer);
}
totalAmountContainer.innerText = `Tổng cộng: ${amount} VND`;
}
function clearCartHandler() {
localStorage.removeItem("cartItems");
updateCartUI();
}
function checkoutHandler() {
alert("Đã thanh toán thành công!");
resetCart();
updateCartUI();
}
function resetCart() {
localStorage.removeItem("cartItems");
}
/*=============== USER MENU FUNCTIONS ===============*/
function showUserMenu() {
// Cập nhật thông tin user
updateUserMenuInfo();
// Hiển thị menu
userMenuContent.classList.add("show-user-menu");
}
function updateUserMenuInfo() {
const userEmail = localStorage.getItem("userEmail") || "email@example.com";
const userName = extractNameFromEmail(userEmail);
// Cập nhật tên và email
const userNameElement = document.getElementById("user-name");
const userEmailElement = document.getElementById("user-email");
if (userNameElement) {
userNameElement.textContent = userName;
}
if (userEmailElement) {
userEmailElement.textContent = userEmail;
}
}
function extractNameFromEmail(email) {
// Lấy phần trước @ và format thành tên
const name = email.split("@")[0];
// Xử lý các trường hợp đặc biệt
if (name === "dothulieu12") {
return "Thu Liêu";
}
// Format tên từ email
return name.charAt(0).toUpperCase() + name.slice(1).replace(/[0-9]/g, "");
}
/*=============== LOGOUT FUNCTIONALITY ===============*/
document.addEventListener("DOMContentLoaded", function () {
// Kiểm tra trạng thái đăng nhập khi tải trang
checkLoginStatus();
// Xử lý sự kiện đăng xuất
const logoutButton = document.getElementById("logout-button");
if (logoutButton) {
logoutButton.addEventListener("click", handleLogout);
}
// Xử lý các nút khác trong user menu
const viewProfileButton = document.getElementById("view-profile");
const viewOrdersButton = document.getElementById("view-orders");
if (viewProfileButton) {
viewProfileButton.addEventListener("click", () => {
alert("Chức năng thông tin cá nhân đang được phát triển!");
});
}
if (viewOrdersButton) {
viewOrdersButton.addEventListener("click", () => {
alert("Chức năng đơn hàng đang được phát triển!");
});
}
});
function checkLoginStatus() {
const isLoggedIn = localStorage.getItem("isLoggedIn") === "true";
if (isLoggedIn) {
updateUIAfterLogin();
}
}
function handleLogout() {
// Hiển thị xác nhận đăng xuất
const confirmLogout = confirm("Bạn có chắc chắn muốn đăng xuất?");
if (confirmLogout) {
// Xóa thông tin đăng nhập
localStorage.removeItem("isLoggedIn");
localStorage.removeItem("userEmail");
// Đóng user menu
userMenuContent.classList.remove("show-user-menu");
// Cập nhật UI về trạng thái chưa đăng nhập
updateUIAfterLogout();
// Hiển thị thông báo
showLogoutMessage();
}
}
function updateUIAfterLogout() {
const loginButton = document.getElementById("login-button");
if (loginButton) {
loginButton.classList.remove("ri-user-3-fill", "logged-in");
loginButton.classList.add("ri-user-line");
loginButton.title = "Đăng nhập";
}
}
function showLogoutMessage() {
// Tạo thông báo đăng xuất
const messageDiv = document.createElement("div");
messageDiv.className = "logout-message";
messageDiv.innerHTML = `
<div class="logout-message__content">
<i class="ri-check-line"></i>
<span>Đăng xuất thành công!</span>
</div>
`;
document.body.appendChild(messageDiv);
// Hiển thị animation
setTimeout(() => {
messageDiv.classList.add("show");
}, 100);
// Tự động ẩn sau 3 giây
setTimeout(() => {
messageDiv.classList.remove("show");
setTimeout(() => {
if (messageDiv.parentNode) {
messageDiv.remove();
}
}, 300);
}, 3000);
}
/*=============== PRODUCT DETAIL FUNCTIONALITY ===============*/
document.addEventListener("DOMContentLoaded", function () {
// Gallery functionality
const galleryThumbs = document.querySelectorAll(".gallery-thumb");
const mainImage = document.querySelector(".product-detail__image-main img");
if (galleryThumbs.length > 0 && mainImage) {
galleryThumbs.forEach((thumb) => {
thumb.addEventListener("click", function () {
// Remove active class from all thumbnails
galleryThumbs.forEach((t) => t.classList.remove("active"));
// Add active class to clicked thumbnail
this.classList.add("active");
// Change main image
mainImage.src = this.src;
mainImage.alt = this.alt;
});
});
}
// Quantity controls
const qtyMinus = document.querySelector(".qty-minus");
const qtyPlus = document.querySelector(".qty-plus");
const qtyInput = document.querySelector(".qty-input");
if (qtyMinus && qtyPlus && qtyInput) {
qtyMinus.addEventListener("click", function () {
let currentValue = parseInt(qtyInput.value);
if (currentValue > 1) {
qtyInput.value = currentValue - 1;
}
});
qtyPlus.addEventListener("click", function () {
let currentValue = parseInt(qtyInput.value);
qtyInput.value = currentValue + 1;
});
qtyInput.addEventListener("change", function () {
if (this.value < 1) {
this.value = 1;
}
});
}
// Add to cart functionality
const addCartBtn = document.querySelector(".btn-add-cart");
const buyNowBtn = document.querySelector(".btn-buy-now");
const wishlistBtn = document.querySelector(".btn-wishlist");
if (addCartBtn) {
addCartBtn.addEventListener("click", function () {
const quantity = qtyInput ? qtyInput.value : 1;
alert(`Đã thêm ${quantity} sản phẩm vào giỏ hàng!`);
});
}
if (buyNowBtn) {
buyNowBtn.addEventListener("click", function () {
const quantity = qtyInput ? qtyInput.value : 1;
alert(`Mua ngay ${quantity} sản phẩm!`);
});
}
if (wishlistBtn) {
wishlistBtn.addEventListener("click", function () {
const icon = this.querySelector("i");
if (icon.classList.contains("ri-heart-line")) {
icon.classList.remove("ri-heart-line");
icon.classList.add("ri-heart-fill");
this.style.color = "var(--first-color)";
alert("Đã thêm vào danh sách yêu thích!");
} else {
icon.classList.remove("ri-heart-fill");
icon.classList.add("ri-heart-line");
this.style.color = "";
alert("Đã xóa khỏi danh sách yêu thích!");
}
});
}
});
/*=============== CATEGORY SCROLL ANIMATION ===============*/
document.addEventListener("DOMContentLoaded", function () {
// Intersection Observer cho category headers
const categoryHeaders = document.querySelectorAll(
".featured__category-header"
);
const observerOptions = {
threshold: 0.3,
rootMargin: "0px 0px -50px 0px",
};
const categoryObserver = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
entry.target.style.animation = "fadeInUp 0.8s ease forwards";
}
});
}, observerOptions);
categoryHeaders.forEach((header) => {
header.style.opacity = "0";
header.style.transform = "translateY(30px)";
categoryObserver.observe(header);
});
});