Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .click() not working properly [duplicate]

I have looked through a few of the other stackoverflow questions about the .click function not working but none of them seem to help me. I have my imports of the jquery libraries.

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

Here is my jquery and im not sure why this isnt working. I have it so it waits till the page is loaded to attempt to run. And i have the class on that element but it doesnt 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 with that i am trying to add the classes to and remove them on the 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 trouble with jquery and I think i am referencing everything ok i know the remove class works if i add that statement to a function called on a click but i dont want to have onclick functions within the a element. Is my syntaxed messed up or maybe im referencing the jquery libraries wrong?

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');
        });
like image 897
Alex Beyer Avatar asked Jun 05 '26 16:06

Alex Beyer


1 Answers

You don't need the entire hierarchy at all times. You can simply remove the class from all a tags within the nav, 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>
like image 72
Paul Roub Avatar answered Jun 08 '26 11:06

Paul Roub