Search code examples
jqueryaddclassremoveclass

addClass & removeClass in nav.php


I have a nav.php in my root that I call within each page using

This way I can edit in one file and the change takes effect throughout the whole site. I am trying to removeClass on a mouse click and addClass on newly click menu item. Below is the code, and I just can't get it to work.

<script>
    $('li').click(function(){
        $('li.active').removeClass('active');
            $(this).addClass('active');
    });
</script>

Here is the URL

http://newriverreleasing.com

Thanks


Solution

  • There are several issues with this...

    The query selector $('li') will surely match more than one element on the page, so you'll need to iterate through all of them and add the click() function, something like:

    $('li').each(function() {
      $(this).click(function(thisLi) {
        // assuming there is only one li.active...
        $('li.active').removeClass('active');
        thisLi.addClass('active');
      });
    });
    

    Also, you need to load this onto the elements that it matches by putting it in a $(document).ready() function, or similar:

    $(document).ready(function() {
        $('li').each(function() {
          $(this).click(function(thisLi) {
            // assuming there is only one li.active...
            $('li.active').removeClass('active');
            thisLi.addClass('active');
          });
        });
    });