Search code examples
javascriptjqueryjquery-easing

jQuery: offset() animation and ajax


I'm having a little problem with jQuery ajax and an animation. I have a layout with a menu that call my page and when loaded, provide a little animation with jQuery easing

Here's my ajax.js

$(document).ready(function() {

    // Ajax request
    $(".transition").click(function() {
      page = ( $(this).attr("id") );
      $.ajax({
        type: "GET",
        url: page,
        data: "ajax=true",
        cache: false,
        success: function(html) {
          afficher(html);
        },
        error: function(XMLHttpRequest,textStatus,errorThrows) {
          // Erreur durant la requête
        }
      });
    });

    function afficher(donnees) {
      $(".step").empty();
      $(".step").append(donnees);

      // Animate
      var step_position = $(".step").offset();
      $(".step").offset({ top: step_position.top, left: step_position.left - 1000 });
      $(".step").animate({
          "left": '+=1000',
        }, 750, 'easeOutBack');
    }
});

If a user clicks, everything work great.

But if:

  • A user double clicks on the same link
  • A user clicks fast on several links

then the loaded data goes out of the page.

I know there's a problem with the fact that I work with asynchronous data and that I ask for the offset at a precise time. I tried to put constant as parameters (instead of doing var step_position = $(".step").offset(); ) but that didn't work.

How should I do for always displaying my data correctly, no matter how many ajax calls are made?


Solution

  • Moi aussi!

    Yep had the same problem - it's called a race condition. I had a button - I don't know if you are using one?

    What I did was in the click handler the first thing I did was disable the button by using the JQUERY .attr() function - adding the disable attribute.

    This had the effect of preventing the second click from doing anything. I re-enabled the button when the ajax came back with a result. In this case you'll have to use a callback somewhere after the animation to reenable the button.