2
votes

I am sliding content when the corresponding header is clicked using slidetoggle. Now I want to toggle between classes simultaneously.

I can use toggleclass and have all of the classes toggled irrespective of which one of the header is clicked, but I'm having trouble in toggling only the class corresponding to the headerclicked.

Here is my code:

<div class="Title ">
  <a class="Expanded" href="#">Title1<span id="span1" class="ArrowDown"></span></a>
</div>
<ul class="Content">
  <a href="#">
  <li class="selected">hello1</li></a> <a href="#">
  <li>hello2</li></a> 
</ul>

<div class="Title">
  <a class="Expanded" href="#">Title2<span id="span2" class="ArrowDown"></span> </a>
</div>
<ul class="Content">
  <a href="#">
    <li>hello3</li></a>
  <a href="#">
    <li>hij</li></a>
  </ul>

Here is my script:

$(document).ready(function(){
  $(".Title").click(function(){
    $(this).next(".Content").slideToggle("slow");
    $("#span1").toggleClass("ArrowUp", "ArrowDown");
  });
});

I just put the id of the first span here, but I tried different things, but couldn't figure out what to do... I want the class of span toggled between ArrowUp and ArrowDown when the corresponding title is clicked (expanded or collapsed).

3

3 Answers

2
votes

You can also use the power of jQuery chaining to write this in a single line like so.

$(this).find('span').toggleClass("ArrowUp", "ArrowDown").end()
       .next(".Content").slideToggle("slow")
       ;

The two things to note in this are .find() (which gets the descendants of matched elements filtered by a selector) and .end() (which ends the most recent filtering operation in the current chain and returns the set of matched elements to its previous state.)

2
votes

In the click callback function, make use of the this keyword, and combine it with the power of the .find() method.

example:

$('element').click(function() {
  $(this).find('span').toggleClass('myclass');
});
1
votes
$(this).find(' span').toggleClass("ArrowUp", "ArrowDown");