870755b570
Lỗi: sidebar.js dùng DOMContentLoaded nhưng script được load động sau khi sự kiện này đã kích hoạt → initSidebar() không bao giờ chạy → nút menu không có event listener → click không phản hồi. Sửa: gọi initSidebar() trực tiếp thay vì bọc trong DOMContentLoaded.
74 lines
2.2 KiB
JavaScript
74 lines
2.2 KiB
JavaScript
// views/components/sidebar/sidebar.js
|
|
// NOTE: This script is always loaded dynamically by sidebarLoader.js AFTER
|
|
// the sidebar HTML has already been injected into #sidebar-container.
|
|
// DOMContentLoaded has already fired at this point, so we must call
|
|
// initSidebar() directly — NOT inside a DOMContentLoaded listener.
|
|
|
|
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;
|
|
});
|
|
}
|
|
|
|
// Call directly — sidebar HTML is already in DOM when this script executes
|
|
initSidebar();
|