I know i can do it with preventDefault, but i don't know where to set the preventDefault on the code...
let navbar = document.querySelector(".navbar");
document.querySelector("#menu-btn").onclick = () => {
navbar.classList.toggle('active');
}
window.onscroll = () => {
navbar.classList.remove("active");
}
let hearts = document.querySelectorAll(".icons a");
hearts.forEach(a => {
a.addEventListener("click", ()=> {a.classList.toggle("color");}
)
})
i think it is in the hearts.forEach block but i don't know where to put it
CodePudding user response:
By restarting, I assume you mean refreshing the page (or navigating to some other pages in the case of a hyperlink)
You need to register the preventDefault in the listener, so the below should work (notice you receive an event argument in the event callback:
hearts.forEach(a => {
a.addEventListener("click", (event) => {
event.preventDefault();
a.classList.toggle("color");
})
})
Event.preventDefault documentation for reference
CodePudding user response:
If you are trying to prevent the click event then:
hearts.forEach(a => {
a.addEventListener("click", (e) => {
e.preventDefault()
a.classList.toggle("color")
}
)
})