I\'m trying to add dynamic active class to my main menu, but i can\'t able to achieve this,
My jquery is,
^^ same as above comment by Rory!!
, if you still need you can do
$("#navi a").live("click", function(){
$("#navi a").removeClass("active");
$(this).addClass("active")
});
If you have all the links pointing to a same page above solution works, as i see you going to traverse from one page to another this wont work.
Thanks
Your description is not very clear. By active if you mean the list-item you are hovering on then it should be something like this:
$('a.menu').hover(
function () {
$(this).addClass("active");
},
function () {
$('a.menu').removeClass("active");
});
Try this
<ul id="navi">
<li><a class="menu" href="#">About MHG</a></li>
<li><a class="menu" href="#">Workout Programs</a></li>
<li><a class="menu" href="#">Fitness Tips</a></li>
<li><a class="menu" href="#">Contact Us</a></li>
<li><a class="menu" href="#">Read Our Blog</a></li>
</ul>
jquery
$('a.menu').click(function(){
$('a.menu').removeClass("active");
$(this).addClass("active");
});
check this Fiddle http://jsfiddle.net/9nd4j/1/
This method will check the page URL that the user is visiting, then add the active class in <li>
tag.
HTML
<div id="nav">
<ul>
<li><a href="index.php">Home</a></li>
<li><a href="about.php">About</a></li>
<li><a href="member.php">Member</a></li>
<li><a href="project.php">Project</a></li>
<li><a href="activity.php">Activity</a></li>
</ul>
</div>
JS
var setActive = function () {
// Get the last item in the path (e.g. index.php)
let url = window.location.pathname.split('/').pop();
// Add active nav class based on url
$("#nav ul li a").each(function () {
if ($(this).attr("href") == url || $(this).attr("href") == '') {
$(this).closest('li').addClass("active");
}
})
// Add the active class into Home if user omit index.php from url
if (url == '') {
$("#nav ul li").eq(0).addClass("active");
}
};
$(function () {
setActive();
});