What am I trying to achieve? I am attempting to use jQuery to dynamically highlight the current page from the navigation bar.
Am I new to jQuery/HTML? Yes, please excuse my lack of experience in this area.
Have I exhausted all resources looking for a solution? Absolutely! I have searched through various StackOverflow posts but haven't been able to find a working solution for my specific issue.
- Navbar highlight for current page
- How to make css a:active work after the click?
- jQuery current page highlight
- highlighting the current page in a list of links using css / html
What's the issue at hand? My problem lies in trying to keep the selected section of my navigation bar highlighted in green once it has been clicked on by the user.
I have successfully implemented hover-over functionality, however, maintaining that color post-click seems to be elusive.
For your information, I am currently using #links and links.html in my "navigation menu" to cater to both scenarios, although ultimately I plan to have separate menus for .html pages and #sections within a page.
Did I provide a simple example to replicate the problem? Yes, see below
index.html:
<!DOCTYPE html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel="stylesheet" href="test_main.css">
</head>
<body>
<div class="navigation">
<a href="test.html">Home</a>
<a href="#section_a">Section A</a>
<a href="#section_b">Section B</a>
</div>
<script>
$(function(){
$('a').each(function(){
if ($(this).prop('href') == window.location.href) {
$(this).addClass('active'); $(this).parents('li').addClass('active');
}
});
});
</script>
<p>Example text</p>
</body>
main.css:
/* Add a white background color to the top navigation */
.navigation {
background-color: #555555;
color: #ffffff;
overflow: hidden;
}
/* Style the links inside the navigation bar */
.navigation a {
float: left;
background-color: #555555;
color: #ffffff;
text-align: center;
padding: 14px 16px;
text-decoration: none;
font-size: 17px;
}
/* Change the color of links on hover */
.navigation a:hover {
background-color: #000000;
color: #ffffff;
}
.active {
background-color: #00ff00;
color: #00000
}
I am aware that a static solution involving setting class="active" within the navigation class could work, but I find this to be cumbersome and less maintainable in the long run.