I am currently working on a dynamic menu system that changes the style of the active page item in the menu. My approach involves utilizing separate body classes for each page and then iterating through the li
elements in the menu to find a match with the body class. Once a match is found, I intend to apply new styling to that specific menu item.
Below is the code I have developed so far:
HTML
<body class="home-state">
...
<div class="menu-left">
<ul>
<li class="home-state">
<a href="/">Home</a>
</li>
<li class="work-state">
<a href="/work">Work</a>
</li>
<li class="services-state">
<a href="/services">Services</a>
</li>
<li class="about-state">
<a href="/about">About</a>
</li>
<li class="blog-state">
<a href="//blog.example.com" target="_blank">Blog</a>
</li>
<li class="shop-state">
<a href="/shop">Shop</a>
</li>
<li class="contact-state">
<a data-toggle="modal" href="#modal-coworking">Contact</a>
</li>
<li class="project-state">
<a href="/brief/index">Project brief</a>
</li>
</ul>
</div>
...
</body>
JS
var bodyClass = $("body").attr('class');
$('.menu-left ul li').each(function(){
First: In this section, my aim is to identify the element's class using $(this).attr("class");
, but I encountered some issues
var element = $(this);
Second: I plan to implement an if statement to validate whether the class matches the bodyClass
console.log(element);
Last: Upon finding a match, I will assign the class .active
to the respective li
element.
});