scandir
scandir

Reputation: 313

addClass() not working as expected in if clause in jQuery

I'm pretty new to jQuery and I have the following problem. So, I want jQuery to listen when the user clicks on the li element and if the element already has class of active it should return from the function. If an element doesn't have a class of active then, it should add a class to it. So, what I want is to add class when the element is clicked but only one element at the time can have the class of active. But right now, my code is adding active class to every element I click. Down below is the code:

<div class="container-fluid">
    <div class="col-sm-2">
        <ul class="nav nav-pills nav-stacked">
            <h3>Lists</h3>
            <hr class="divider">
            <li><a href="#"><span class="glyphicon glyphicon-briefcase"></span> Work</a></li>
            <li><a href="#"><span class="glyphicon glyphicon-plane"></span> Travel</a></li>
            <li><a href="#"><span class="glyphicon glyphicon-book"></span> School</a></li>
        </ul>
    </div>
</div>

</div>

<script>
    (function () {

        $('.nav').children('li').on('click', function () {
            $this = $(this);

            if ( $this.hasClass('active') ) {
                return 0;
            } else {
                $this.addClass('active');
            }

        });

    })();
</script>

Upvotes: 0

Views: 87

Answers (4)

Elena
Elena

Reputation: 399

You can do somethink like this for example:

(function () {
     $('.nav').on('click', 'li', function () {
         $(this).toggleClass('active')
             .siblings('li').removeClass('active');
     });

 })();

this inside the event handler refers only to the DOM element on which event was triggered (to li that was clicked in our case). If you log this inside your callback function you'll see that it refers only to the one li element (which is clicked):

 (function () {
        $('.nav').children('li').on('click', function () {
            console.log(this); //logs <li class="active"> </li>
            //other code
    })();

Upvotes: 1

FrEaKmAn
FrEaKmAn

Reputation: 1845

Basically we add class and remove class from all siblings.

(function () 
{
    $('.nav').on('click', 'li', function() 
    {
        $(this).addClass('active')
               .siblings('li')
               .removeClass('active');
    });
})();

Upvotes: 0

Jay Blanchard
Jay Blanchard

Reputation: 34406

Try it like this -

$('.nav').children('li').on('click', function () {
   $('.nav').children('li').removeClass('active');
   $(this).addClass('active');

});

Upvotes: 0

kefy
kefy

Reputation: 535

Try this

    $(function(){
        $('.nav li').click(function () {
             $('.nav li').removeClass("active");    
             $(this).addClass("active");    
        });
   });

Upvotes: 2

Related Questions