1

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>
3
  • If you are using accordion from jQueryUI, you already have an active class on it. Commented Sep 13, 2016 at 11:31
  • I think you need to start accepting some answers on your questions - this is the 3rd question you have asked where you are yet to accept anything or really respond to any of the people that have taken the time to try and help you. Commented Sep 13, 2016 at 22:43
  • Possible duplicate of jQuery onclick toggle class name Commented Sep 13, 2016 at 22:58

6 Answers 6

3

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>

Sign up to request clarification or add additional context in comments.

Comments

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

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

2 Comments

You used @RahulPatel solution.
@Mohammad hadn't seen his answer at that point, I answered seconds after him
0

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).

Comments

0

Check if it works

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

Comments

0

you have to give your list an id

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

Comments

0

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("-");
   }
 });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.