0

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

Community
  • 1
  • 1
Nick
  • 1,193
  • 13
  • 24
  • 37

2 Answers2

5

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

DanielB
  • 18,800
  • 2
  • 41
  • 49
  • this is great, thanks! think i'll go with this, I like the way it keeps track of the state too so if you spam the toggle button it'll always end on the right class :) – Nick May 19 '11 at 13:53
1

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.

Paul Fleming
  • 22,772
  • 8
  • 65
  • 107
James Montagne
  • 73,502
  • 13
  • 107
  • 127
  • this is a great idea, thank you - i like the idea of keeping track of the state via show/hide too – Nick May 19 '11 at 13:53