I have a custom animation that when you hover a link a line flows from left to right (See example: https://jsfiddle.net/mxfiddle/fubLo45j/2/ ).
I want the line to stay for the current page I am on.
I am totally new to web development in general so any help would be much appreciated.
Thanks in advance.
My code for adding an active class:
// Get the container element
var navbarContainer = document.getElementById("navbar");
// Get all navbar elements with class="navElement" inside the container
var navElement = navbarContainer.getElementsByClassName("navElement");
// Loop through the navbar elements and add the active class to the current/clicked button
for (var i = 0; i < navElement.length; i++) {
navElement[i].addEventListener("click", function() {
var current = document.getElementsByClassName("active");
current[0].className = current[0].className.replace(" active", "");
this.className += " active";
});
}
Add this to your pages:
document.body.onload = function() {
// on page load
document.querySelectorAll("#navbar a").forEach(a => {
//catch all links in navbar
a.href === location.pathname ? a.classList.add("active") : a.classList.remove("active")
// if navbar link is the same as current loacation pathname add active class, if not remove it.
})
};
You need ether something like this or saving clicked item in local storage and read it on other page...
And I hope you do understand you can simply remove active class from home and put on a current link in HTML depending on page you are on...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.