Ok maybe the title is worded a bit wrong...
I have some javascript that is supposed to open my sidebar once the button is clicked - But it is taking two clicks to open the sidebar and another two clicks to close..
I understand why this is happening via my Javascript - But not sure on the remedy (Not sure if its actually a Blazor issue?)
Javascript
function LoadContent() {
document.addEventListener("DOMContentLoaded",
document.onclick = function(event) {
const showNavbar = (toggleId, navId, pId, headerId) => {
const toggle = document.getElementById(toggleId),
nav = document.getElementById(navId),
bodypd = document.getElementById(pId),
headerpd = document.getElementById(headerId);
mainbodypd = document.getElementById("mainbody");
if (toggle && nav && bodypd && headerpd && mainbodypd) {
toggle.addEventListener("click",
() => {
nav.classList.toggle("show");
toggle.classList.toggle("bx-x");
bodypd.classList.toggle("body-pd");
headerpd.classList.toggle("body-pd");
mainbodypd.classList.toggle("height-100short");
});
}
};
showNavbar("header-toggle", "nav-bar", "body-pd", "header");
const linkColor = document.querySelectorAll(".nav_link");
function colorLink() {
if (linkColor) {
linkColor.forEach(l => l.classList.remove("active"));
this.classList.add("active");
}
}
linkColor.forEach(l => l.addEventListener("click", colorLink));
});
}
Can anyone explain, how i can prevent this from happening (Sorry, i am fairly new to JS)
So why are you doing:
document.onclick = function(event) {
This makes the function trigger every page click ANYWHERE on the page (meaning you keep adding event listeners every time you click).
You should probably remove that part, or if you need it for something, take the shownavbar section out of it and just have it in DOMContentLoaded