New coder here and would really appreciate your help with a problem that's got me stumped.
I'd like to write code that will recognize the link that applies to the current page and applies a different CSS style to that current link. I've researched this problem and have found that it's best accomplished using jQuery to identify the current link and then apply a new class to it (e.g., ".current"). However, when I've tried to implement this on the site it hasn't worked.
This is the HTML I'm working with:
<nav class="main-nav">
<a href="http://website.com" class="main-nav-link">
<span class="main-nav-item" id="nav-content"></span>
</a>
<a href="http://website.com/calendar" class="main-nav-link">
<span class="main-nav-item" id="nav-calendar"></span>
</a>
<a href="http://website.com/profile" class="main-nav-link">
<span class="main-nav-item" id="nav-profile"></span>
</a>
</nav>
And this is the CSS I've applied:
.main-nav .main-nav-item {
height: 50px;
width: 150px;
}
.main-nav #nav-content {
background: url('/images/content-inactive.png') no-repeat center;
}
.main-nav #nav-calendar {
background: url('/images/calendar-inactive.png') no-repeat center;
}
.main-nav #nav-profile {
background: url('/images/profile-inactive.png') no-repeat center;
}
My goal is to change the background:
for the span within the current page's <a>
.
Here are some other StackOverflow threads that have addressed this problem, but haven't helped me to reach a solution:
It's not completely clear to me where I'm supposed to be putting the Javascript, but I currently have it between <script type="text/javascript">
and </script>
in the <header>
section.
Thanks in advance for your assistance. :)
--
UPDATE:
I currently have the following code in the page, but it's not working.
The Javascript:
<script>
$(document).ready(function() {
// Get the current URL
var currentUrl = window.location.href;
// Get the span you want with a combination class and attribute and child jQuery selector
var currentMenuItem = $(".main-nav-link[href='" + currentUrl + "'] > .main-nav-item");
// Then add your class
currentMenuItem.addClass("current");
});
</script>
And the CSS:
#nav-content.current {
background: url('/images/content-active.png') no-repeat center -94px;
}
The jQuery isn't adding the .current
class to the active link, so the CSS doesn't even have the opportunity to work.