Alex
Alex

Reputation: 68492

jQuery toggle() problem

  $('.toggle').toggle(function(){
    var ul = $('ul');
    ul.fadeOut('fast', function(){
      ul.fadeIn('fast').removeClass('off');
      ul.addClass('on');
    });
  }, function(){
    ul.fadeOut('fast', function(){
      alert('wtf'); // <- never gets here...
      ul.fadeIn('fast').removeClass('on');
      ul.addClass('off');
    });
  });

What am I doing wrong??

Any code that I add inside the second fadeOut callback function never gets executed...

Upvotes: 2

Views: 356

Answers (3)

Hamish
Hamish

Reputation: 23316

The variable ul doesn't exist in the scope of the second function. It's actually a bit of an unneeded optimization in your case, since the following should also work:

  $('.toggle').toggle(function(){
    $('ul').fadeOut('fast', function(){
      $(this).fadeIn('fast').removeClass('off').addClass('on');
    });
  }, function(){
    $('ul').fadeOut('fast', function(){
      $(this).fadeIn('fast').removeClass('on').addClass('off');
    });
  });

Upvotes: 2

Plynx
Plynx

Reputation: 11461

Put var ul = $('ul'); in your second function too.

Upvotes: 3

alex
alex

Reputation: 490243

ul is not defined in the second callback. Change its scope so it is visible to both callbacks.

var ul = $('ul');

$('.toggle').toggle(function(){
  ul.fadeOut('fast', function(){
    ul.fadeIn('fast').removeClass('off');
    ul.addClass('on');
  });
}, function(){
  ul.fadeOut('fast', function(){
    ul.fadeIn('fast').removeClass('on');
    ul.addClass('off');
  });
});

If you don't want ul to be in scope outside of this, either wrap it in a self invoking function or specify the ul within each callback of toggle().

Upvotes: 2

Related Questions