1

I have the following Coffeescript code:

# Coffeescript
setMessage = (message, options = {}) -> 
  t = statusArea.text(message)
  if options['fade']
    t.addClass('yellow')
    t.fadeOut 4000, ->
      $(this).removeClass 'yellow'

// Javascript
setMessage = function(message, options) {
  var t;
  if (options == null) options = {};
  t = statusArea.text(message);
  if (options['fade']) {
    t.addClass('yellow');
    return t.fadeOut(4000, function() {
      return $(this).removeClass('yellow');
    });
  }
};

which is meant to display a status message inside a LI element. If options['fade'] is set to anything, then I invoke the fading stuff. The first thing that happens in my program flow is that I issue an Ajax call to populate a SELECT and post a "making remote call" message with a fade (i.e., with options['fade'] set to true) to the status area. This can be almost instantaneous or it can take a while. It depends on the size of the result and network traffic. Once the SELECT is populated, I post a "ready" message without a fade.

The problem occurs when the response is almost instantaneous. In that case, the text is replaced with "ready" but the animation continues, fading the message out (i.e., fading the LI element out).

Is there an accepted way to terminate the previous transition, if any, before starting another one?

Steve Ross
  • 4,134
  • 1
  • 28
  • 40
  • Flagged as duplicate: http://stackoverflow.com/questions/1421298/how-do-you-cancel-a-jquery-fadeout-once-it-has-began – Aaron Dufour Mar 06 '12 at 05:43
  • 1
    Notice I said *Zepto*, not jQuery in my title. The answer cited here addresses jQuery, but not Zepto, which is missing a stop() function. I added a stop() function in my branch at https://github.com/sxross/zepto/commit/0389dd532c7d5f93e7586210d6708bd24922d3ff, but hoped there was some better way. – Steve Ross Mar 06 '12 at 17:21

1 Answers1

0

I don't know how you implemented the stop() function, but the most reliable way would probably to remove the node's cssText completely.

I've created a fiddle to demonstrate 3 implementations. The problem with the first 2 implementations is that you will need to know which property is currently animating and also it's original value - although you could also implement this by just removing said property from the node's css text to use whichever style applies.

To cancel Zepto animations something like this should suffice:

$.fn.stop = function() {
    $(this).each(function() {
        $(this)
            .off("webkitTransitionEnd webkitAnimationEnd")
            .get(0).style.cssText = "";
        }
    });
    return this;
};

However, a side effect of this would be that previous style changes with zepto would be removed as well. A meaningful robust stop function should also be part of an animation queue to have access to animated properties as well.

Torsten Walter
  • 5,614
  • 23
  • 26