Nick
Nick

Reputation: 1243

jQuery - testing slideToggle state with an animation?

I've used some of the information here to create a toggle state check, which worked fine with a regular instant toggle, but how do I apply it to a slideToggle with slow animation? Here's my code:

$('#elemToggle').click(function() {
    $("#elem").slideToggle('slow');
    if($("#elem").is(":visible")) {
        $('#elemToggle').addClass('down');
        $('#elemToggle').removeClass('up');
    } else {
        $('#elemToggle').addClass('up');
        $('#elemToggle').removeClass('down');
    }
    return false;
});

The above doesn't work since when you hit the button, technically the elem is still visible and just being collapsed. Any ideas for a workaround please?! :)

Thanks

Upvotes: 0

Views: 1542

Answers (2)

James Montagne
James Montagne

Reputation: 78650

You could just move the test before the toggle and invert it. If the element is visible before the toggle then you know it is going to be hidden and the same for the opposite.

Although from the looks of it, I would probably not use toggle for this and instead use show and hide and keep track of the state myself.

Upvotes: 1

DanielB
DanielB

Reputation: 20240

do your check on the complete callback of slideToggle()

$('#elemToggle').click(function() {
    $("#elem").slideToggle('slow', function() {
      if($("#elem").is(":visible")) {
        $('#elemToggle').addClass('down');
        $('#elemToggle').removeClass('up');
      } else {
        $('#elemToggle').addClass('up');
        $('#elemToggle').removeClass('down');
      }
    });
    return false;
});

Here the Documentation

Upvotes: 5

Related Questions