forked from MinhQuan/PresentCorpo
Refactor: Extract sidebar into a reusable component
This commit is contained in:
@@ -0,0 +1,69 @@
|
||||
// views/components/sidebar/sidebar.js
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
initSidebar();
|
||||
});
|
||||
|
||||
function initSidebar() {
|
||||
const floatingMenuBtn = document.getElementById("floatingMenuBtn");
|
||||
const sidebarOverlay = document.getElementById("sidebarOverlay");
|
||||
const sidebar = document.getElementById("sidebar");
|
||||
const closeSidebarBtn = document.querySelector(".close-sidebar");
|
||||
|
||||
function openSidebar() {
|
||||
if (sidebar && sidebarOverlay) {
|
||||
sidebar.classList.add("open");
|
||||
sidebarOverlay.style.display = "block";
|
||||
}
|
||||
}
|
||||
|
||||
function closeSidebar() {
|
||||
if (sidebar && sidebarOverlay) {
|
||||
sidebar.classList.remove("open");
|
||||
sidebarOverlay.style.display = "none";
|
||||
}
|
||||
}
|
||||
|
||||
if (floatingMenuBtn) {
|
||||
floatingMenuBtn.addEventListener("click", openSidebar);
|
||||
}
|
||||
|
||||
if (closeSidebarBtn) {
|
||||
closeSidebarBtn.addEventListener("click", closeSidebar);
|
||||
}
|
||||
|
||||
if (sidebarOverlay) {
|
||||
sidebarOverlay.addEventListener("click", closeSidebar);
|
||||
}
|
||||
|
||||
// Close sidebar when clicking outside or on a link
|
||||
document.addEventListener("click", (e) => {
|
||||
if (sidebar && sidebar.classList.contains("open")) {
|
||||
// Click outside sidebar and not on floating menu button
|
||||
if (
|
||||
!sidebar.contains(e.target) &&
|
||||
!e.target.closest("#floatingMenuBtn")
|
||||
) {
|
||||
closeSidebar();
|
||||
}
|
||||
// Click on a nav link
|
||||
if (e.target.closest(".sidebar-nav .nav-link")) {
|
||||
closeSidebar();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Handle scroll behavior to hide/show floating menu button smoothly
|
||||
let lastScrollY = window.scrollY;
|
||||
window.addEventListener("scroll", () => {
|
||||
if (window.innerWidth <= 768 && floatingMenuBtn) {
|
||||
if (window.scrollY > lastScrollY && window.scrollY > 100) {
|
||||
// Scrolling down
|
||||
floatingMenuBtn.style.display = "none";
|
||||
} else {
|
||||
// Scrolling up
|
||||
floatingMenuBtn.style.display = "flex";
|
||||
}
|
||||
}
|
||||
lastScrollY = window.scrollY;
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user