Gene9y
Gene9y

Reputation: 859

How to toggle class between two element using jquery?

I have accordian lists with one list open always. How can I toggle the active class when the button is clicked?

<ul class="accordion one-open">
   <li class="active">
       <div class="title">Title 1</div>
       <div class="content">Content 1</div>
   </li>
   <li>
       <div class="title">Title 2</div>
       <div class="content">Content 2</div>
   </li>
</ul>
<button>Toggle the content </button>

Upvotes: 1

Views: 3016

Answers (6)

Novice
Novice

Reputation: 558

I too had faced the same problem. Solved it using icons. Please refer the answer here

This is what I had used before:

if($(this).text() == "-")  
{
  $(this).text("+");
  }
  else {
  $('#accordion .opener').text("+");
  $(this).text("-");
   }
 });

Upvotes: 0

Rahul Patel
Rahul Patel

Reputation: 5244

Use .toggleClass("active") of jquery and check the below snippet.

$(document).ready(function(){
  $("#toggel_class").on('click',function(){
    $("ul li").toggleClass("active");
  });
});
.active { color: red }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="accordion one-open">
   <li class="active">
       <div class="title">Title 1</div>
       <div class="content">Content 1</div>
   </li>
   <li>
       <div class="title">Title 2</div>
       <div class="content">Content 2</div>
   </li>
</ul>
<button id="toggel_class">Toggle the content </button>

Upvotes: 3

Travis Hallet
Travis Hallet

Reputation: 85

you have to give your list an id

$("#item1").click(function(){
    $(".active").removeClass("active");
    $(this).addClass("active")
});

Upvotes: 0

nimaek
nimaek

Reputation: 214

$("button").on("click", function() {
   $("li").toggleClass("active");
});

This toggles the class when the button is clicked: https://jsfiddle.net/mqhyLohe/

Upvotes: 1

MKB
MKB

Reputation: 815

Check if it works

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

Upvotes: 0

Giel Berkers
Giel Berkers

Reputation: 2960

Try looking at JavaScript classList.toggle() (not compatible with IE9 and lower). Otherwise take a look at jQuery UI (if jQuery is the path you want to wander).

Upvotes: 0

Related Questions