Search code examples
javascriptajaxscriptaculousprototypejs

Fade out, update by AJAX, fade in a div using Prototype


I have a div whose contents I want to update by AJAX. To make the transition smooth, I'd like to fade out the old contents, then update it with the AJAX response, then fade it back in.

My first attempt is as follows; but of course the AJAX can complete before the fade() call, resulting in appear() not firing properly and the end-state being faded out. How can I make this work as I want?

target = $('card_text_' + index);
new Ajax.Request('/games/card_text', 
         {asynchronous:false, 
          evalScripts:true, 
          method:'get', 
          parameters:'type=' + value,
          onCreate: function(){target.fade()},
          onSuccess: function(e){target.update(e.responseText).appear()}
          });

Edit: For completeness, I'm using Prototype with script.aculo.us


Solution

  • I have found the solution I wanted, although the docs didn't make it easy. Turns out, all script.aculo.us Effects have a set of callbacks, including afterFinish. My code has become:

    target = $('card_text_' + index);
    new Effect.Fade(target, {afterFinish: function(){
      new Ajax.Updater(target, '/games/card_text', 
               {asynchronous:false, 
                evalScripts:true, 
                method:'get', 
                parameters:'type=' + value,           
                onSuccess: function(e){new Effect.Appear(target)}
                });