Adam Scot
Adam Scot

Reputation: 1409

Toggle class on multiple elements

I have the below unordered list

<ul>
<li class="item">Link 1</li>
<li class="item">link 2</li>
<li class="item">Link 3</li>
</ul>

I am currently using the following javascript to toggle the class "open" to any <li> element with the "item" class referenced.

  $(document).ready(function(){
      $('.item').click(function(){
        $(this).toggleClass('open');
      });
    });

I would like to make it so that the class "open" can only be applied to one "item" element at a time.

Therefore for example: If the user clicks "Link 2" after having already clicked "Link 1". "Link 1" would lose the "open" class and the "open" class would be attributed to "Link 2".

Upvotes: 0

Views: 3778

Answers (1)

Andy Holmes
Andy Holmes

Reputation: 8047

You could do it this way in your jQuery:

 $(document).ready(function() {
   $('.item').click(function() {
     $(this).toggleClass('open');
     $(this).siblings().removeClass('open');
   });
 });

This basically attributes the open class to the item you're clicking while simultaneously removing it from any siblings that have the same class.

Fiddle - https://jsfiddle.net/pnortmrL/

Upvotes: 2

Related Questions