I am exploring how to dynamically add the "active" class to a specific section of my menu based on which link within that section has been clicked. After successfully implementing the active class functionality for individual links using jQuery, I am confident that I can adapt the code to achieve my desired outcome. Below is the code snippet that serves as my reference point.
For instance, when the "lil shorty" link is clicked, I aim for the ul with id="section_3" to receive the active class. Similarly, if "Deriving functions" is selected, I intend for the ul with id="section_2" to be marked as active (while removing the active class from section_3). It is important to note that when navigating to the Deriving functions page, section_2 should retain the "active" class.
Your assistance in this matter would be highly appreciated.
Sincerely, Jack
$(function() {
var pgurl = window.location.href.substr(window.location.href
.lastIndexOf("/") + 1);
$(".section li a").each(function() {
var aurl = $(this).attr("href").substr($(this).attr("href")
.lastIndexOf("/")+1);
if (aurl == pgurl || aurl == '')
$(this).addClass("active");
})
});
<div class="menu">
<ul class='section' id='section_2'>
<li><span id='section_title_2' class='section_title'><a href='#' id='section_link_2'>Against the odds.</a></span>
<ul>
<li id='exhibit_1' class='exhibit_title'><a href="../against-the-odds/introduction"> → Introduction</a></li>
<li id='exhibit_2' class='exhibit_title'><a href='../against-the-odds/deriving-functions'> → Deriving functions</a></li>
<li id='exhibit_3' class='exhibit_title'><a href='../against-the-odds/exploiting-odds'> → Exploiting odds</a></li>
</ul>
</li>
</ul>
<ul class='section' id='section_3'>
<li><span id='section_title_3' class='section_title'><a href='#' id='section_link_3'>Remembering everything.</a></span>
<ul>
<li id='exhibit_104' class='exhibit_title'><a href='#'>black swans</a></li>
<li id='exhibit_104' class='exhibit_title'><a href='#'>lil shorty</a></li>
</ul>
</div>