JQuery.click () not working as expected

I've looked at several other stackoverflow questions about the .click function that doesn't work, but none of them seem to help me. I have import of jQuery libraries.

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

      

Here is my jquery and I'm not sure why it doesn't work. I have this, so it waits for the page to load to try and start. And I have a class on this element, but it does not register the click.

$(document).ready(function() {
            $('nav.product-description-nav ul li a').click(function() {
                $(".product-description-nav ul").find($('li a.active-product-selection')).removeClass('active-product-selection');
                $(this).addClass('active-product-selection');
            });
        });

      

Here is my navigation so that I am trying to add classes and remove them on click.

<nav class="product-description-nav">
    <ul>
        <li><a href="#" class="active-product-selection">Overview</a></li>
        <li><a href="#">Options</a></li>
        <li><a href="#">Downloads</a></li>
        <li><a href="#">Request A Quote</a></li>
    </ul>
</nav>

      

I always have problems with jquery and I think I am referencing everything ok. I know the remove class works if I add this statement to the click-called function, but I don't want to have onclick functions inside the element. Is my syntax flawed or maybe it is wrong for them to reference the jquery libraries?

This is the answer to my problem.

$(document).on('click','.product-description-nav a',function(){
            $(".product-description-nav a").removeClass('active-product-selection');
            $(this).addClass('active-product-selection');
        });

      

+3


source to share


1 answer


You don't need the entire hierarchy at all times. You can simply remove the class from all tags a

in nav

, and then add the class back to this

:



$(document).ready(function() {
  $('nav.product-description-nav a').click(function() {
    $("nav.product-description-nav a").removeClass('active-product-selection');
    $(this).addClass('active-product-selection');
  });
});
      

.active-product-selection {
  color: red;
}
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<nav class="product-description-nav">
  <ul>
    <li><a href="#" class="active-product-selection">Overview</a>
    </li>
    <li><a href="#">Options</a>
    </li>
    <li><a href="#">Downloads</a>
    </li>
    <li><a href="#">Request A Quote</a>
    </li>
  </ul>
</nav>
      

Run codeHide result


+2


source







All Articles