I was looking for tutorials on how to add and remove a class from a link, unfortunately, without any success. All the earlier questions about this give me some understanding, but they donβt give me the result that I want to achieve.
I am trying to have an active state for my navigation by adding and removing a class when a link is clicked.
Here is what I have in JavaScript:
$(document).ready(function(){ //active state $(function() { $('li a').click(function(e) { e.preventDefault(); var $this = $(this); $this.closest('li').children('a').removeClass('active'); $this.parent().addClass('active'); }); }); });
And this is my navigation:
<div id="nav"> <div id="main-nav" class="center"> <ul> <li><a href="/photography.php">Photography</a></li> <li><a href="/web.php">Web</a></li> <li><a href="/print.php">Print</a></li> <li class="nav-R"><a href="/about.php">About</a></li> <li class="nav-R"><a href="/contact.php">Contact</a></li> </ul> </div> </div>
source share