Naor
Naor

Reputation: 24103

jquery toggle classes after animation doesn't work

I have this javascript code: http://jsbin.com/orenim/4/edit

blinkTimes = 0;
function blink () {                           
  $('.a').toggleClass('b');
  blinkTimes --;
  if (blinkTimes > 0) {
    setTimeout(blink, 500);
  }
}

function startBlink() {
  //alert('?');
  blinkTimes = 4;
  blink();
}

$(document).click(function() {
  $('html, body').animate({ scrollTop: top }, '400', 'swing', startBlink);
});

This should toggle '.b' class right after animation. For some unknown reasons the '.a' element doesn't toggled with the class '.b'. If I uncomment the alert('?') the code is work.
What is the problem?

Upvotes: 0

Views: 334

Answers (1)

adeneo
adeneo

Reputation: 318342

$('html, body') selects two elements, firing two callbacks at the same time, which cancels each other out, try just $('body').animate({ .... and see how that works. If you need to select both elements, use a flag to make sure the callback function only runs once.

BIN

or as suggested by undefined, use a promise:

$(document).click(function() {
  $('body, html').animate({ scrollTop: top }, '400', 'swing').promise().done(startBlink)
});

Upvotes: 3

Related Questions