manuxi
manuxi

Reputation: 352

jQuery: toggle an element, after toggling change the class

I'd like to archieve the following: Onclick my next ul in a tree should toggle (works) Thereafter(!) the class should change from treeExpanded to treeCollapsed, but I don't get it...

    ...
    <li>
        <a class="treeExpanded">Toggle</a>
        <span>xyz</span>
        <ul class="steps">
        ...
        </ul>
    </li>
    ...

works, but class is changed immediately:

    $j('.treeExpanded').click (function () {
        $j(this).toggleClass('treeCollapsed','treeExpanded').nextAll('ul').slideToggle("slow");
    });

also works, but class is changed immediately:

    $j('.treeExpanded').click (function () {
        $j(this).nextAll('ul').slideToggle("slow");
        $j(this).toggleClass('treeCollapsed','treeExpanded');
    });

won't work:

    $j('.treeExpanded').click (function () {
        $j(this).nextAll('ul').slideToggle("slow", function () {
            $j(this).parents('a:first').toggleClass('treeCollapsed','treeExpanded');
        });
    });

Upvotes: 0

Views: 228

Answers (2)

Glenn Plas
Glenn Plas

Reputation: 1638

you could try it like this:

  $('.treeExpanded').toggle(function(){ 
     $(this).nextAll('ul').removeClass("treeCollapsed");
     $(this).addClass("treeExpanded");
  }, function(){ 
     $(this).nextAll('ul').removeClass("treeExpanded");
     $(this).addClass("treeCollapsed");
  });

Something along those lines. I find that this works better than messing with click itself.

Upvotes: 0

Musa
Musa

Reputation: 97707

You can save the element in a variable then use it in the callback

$j('.treeExpanded').click (function () {
    $this = $j(this);
    $this.nextAll('ul').slideToggle("slow", function () {
        $this.toggleClass('treeCollapsed','treeExpanded');
    });
});

Upvotes: 1

Related Questions