Jquery Removing & Adding 'Active' Class On LI Navigation Works With preventDefault, But Link No Longer
Jquery removing an adding active class to li nodes not working
I know it should be really basic to remove and add the active class to li's in order to highlight the current page's nav item, but I've been unable to get it to work.
I find that I must use e.preventDefault() to make it work, but when I do the link doesn't work but the highlighted nav item works. If I remove the preventDefault() then it navigates but doesn't highlight. I should say that my nav is sitting in a header.php include file. Here's what I have:
<ul class="myNav">
<li><a href="index.php">Home</a></li>
<li><a href="portfolio.php">Portfolio</a></li>
<li><a href="about.php">About</a></li>
<li><a href="contact.php">Contact</a></li>
</ul>
$('.myNav li a').click(function (e)
{
e.preventDefault();
$('.myNav li').siblings().removeClass('active');
$(this).parent().addClass('active');
//var url = $(this).attr("href");
//window.location = url;
});
I tried to send the page to the clicked url and this loads the correct page, but it removes the class! I'd like to solve this, but I'd also like to understand why it isn't working correctly.
I ended up doing it in PHP like this:
when you navigate out of the page, whatever you did in javascript will be lost. Only way would be for your server program to set the 'active' flag, maybe by adding a query parameter to the link, or by checking the program's url
I am afraid you can't achieve both highlighting and redirecting to the page at the same time using
only
jQuery. You should better try to add classactive
to respectiveli
in your pages for example inindex.php
page add this lineBecause you cant preserve the state of menus using only
jQuery
. If this menu section of your page is in a seperate file likeheader.php
then you have to detect which one is the current page. And can easily detect current page in php and addclass="active"
to correspondingli
to highlight that.You have to do this in PHP by detecting the current url and comparing that the the url of the nodes in your navigation. Check this out: How can I get the current page's full URL on a Windows/IIS server?