I’m using Barba.js for handling page transitions in my website. I have a navigation menu that opens when clicking on a div with the class nav-btn. Everything works perfectly when the page is loaded for the first time, but after transitioning to another page using Barba.js, the click event listener for the navigation menu button no longer works till refresh the page.
Here’s the relevant part of my code:
function navOpener() {
let navbtn = document.querySelector(".nav-btn");
if (navbtn != null) {
console.log("Navopener running...");
console.log(navbtn);
navbtn.addEventListener("click", function () {
console.log("nav opener clicked");
// Other logic here...
});
}
}
When I check the console, I see the message “Navopener running…” and navbtn element after the transition so i am sure navbtn is ok, but the click event listener doesn’t trigger anymore, and the console.log(“nav opener clicked”) never shows up. I am running all the functions beforeEnter. And as i said when refresh the page everything works perfectly.
2
First, I applied the suggested event delegation method, which resolved the issue with the click event listener but nav-menu still not appear after transition. However, I noticed that after each page transition, the click event on nav-btn was stacking up. For example, on the initial load when on the homepage, a single click on nav-btn resulted in one console.log(“nav opener clicked”). After transitioning to the other page, a single click resulted in two console.log(“nav opener clicked”), and after moving to the another page, a single click resulted in three console.log(“nav opener clicked”). So for this i updated my code like below
function openNavMenu() {
if (navOpenMenuInitialized) {
return; // Don't add the event listener again
}
document.addEventListener("click", function (event) {
const navButton = event.target.closest(".nav-btn");
if (navButton) {
console.log("nav opener clicked...");
const bodyElement = document.querySelector("body");
if (bodyElement.classList.contains("nav-open")) {
bodyElement.classList.remove("nav-open");
lenis.start();
} else {
bodyElement.classList.add("nav-open");
lenis.stop();
}
}
});
navOpenMenuInitialized = true;
}
Seems working now.
If you have any further suggestions or improvements, I would greatly appreciate them.