Search code examples
javascriptruby-on-railsruby-on-rails-3.2ujs

Rails 3 UJS run a while loop when waiting for an ajax:callback


This is my javascript for a :remote => true form.

Currently, when the form is submitted, this function runs once. (the width increases by 5%.

However, I want this animation to run in a loop so that the width keeps increasing by increments of 5% until I get an ajax:success or an ajax:failure callback, at which point I want to jump into another function.

$('#new_message').bind('ajax:loading', function() {
  $('#send_bar').animate({
    width: '+=5%'
  });
});

Solution

  • Declare a function that runs the animation, and then in the completion parameter, pass the the function so that it calls itself recursively:

    var start_animation = function() {
      $('#send_bar').animate({width: '+=5%'}, 5000, 'linear', start_animation);
    }
    

    In the loading function, call the function to begin the animation:

    $('#new_message').bind('ajax:loading', function() {
      start_animation();
    });
    

    Then in your bind to ajax:success and ajax:failure, call stop:

    $('#new_message').bind('ajax:success', function() {
      $('#send_bar').stop();
    });
    
    $('#new_message').bind('ajax:failure', function() {
      $('#send_bar').stop();
    });