Reputation: 79
I am able to get the navigation bar to change color for hover, active, and current. The problem is when the page loads it refreshes the navigation bar and the current page color reverts back. I believe the javascript is working as expected.
I found one method of doing this in which each web page has it's own navigation bar, which is not the greatest method of coding and only would be used if there are just a few pages to the website.
/*
* https://www.w3schools.com/howto/howto_js_active_element.asp
*/
// Get the container element
var btnContainer = document.getElementById("navbar");
// Get all buttons with class="btn" inside the container
var btns = btnContainer.getElementsByClassName("btn");
// Loop through the buttons and add the active class to the current/clicked button
for (var i = 0; i < btns.length; i++) {
btns[i].addEventListener("click", function() {
var current = document.getElementsByClassName("current");
// If there's no current class
if (current.length > 0) {
current[0].className = current[0].className.replace(" current", "");
}
// Add the current class to the current/clicked button
this.className += " current";
});
}
/* Change background color of navbar links on hover */
.btn:hover {
background-color: #FFFF00;
/* Yellow */
color: #000000;
/* Black */
}
/* Change background color of navbar links on active */
.btn:active {
background-color: #FF0000;
/* Red */
color: #000000;
/* Black */
}
/* Change background color of navbar links for current page */
.btn.current {
background-color: #006600;
/* Green */
color: #FFFFFF;
/* White */
}
<nav>
...
<div id="navbar" class="navbar">
<div class="dropdown">
<button class="dropbtn"><a class="btn" href="index.php">Home</a>
<i class="fa fa-caret-down"></i>
</button>
</div>
<div class="dropdown">
<button class="dropbtn"><a class="btn" href="PlanYourVisit.php">New Here</a>
<i class="fa fa-caret-down"></i>
</button>
<div class="dropdownContent">
<a class="btn" href="PlanYourVisit.php">Plan Your Visit</a>
<a class="btn" href="YourKids.php">Your Kids</a>
<a class="btn" href="TimeLocation.php">Time and Location</a>
</div>
</div>
...
</div>
</div>
</nav>
I would like the navigation bar to keep the color green for the current page. The navigation turns green, then reverts to the default gray color I have for the navigation bar.
Upvotes: 2
Views: 3984
Reputation: 15847
The key is to do this on page load NOT on click.
Simply loop through your navigation and see if the HREF matches the current URL.
<script>
let current_url = document.location;
document.querySelectorAll(".navbar .btn").forEach(function(e){
if(e.href == current_url){
e.classList += " current";
}
});
</script>
Upvotes: 3