Erik Wahlström Erik Wahlström - 3 months ago 24
Javascript Question

Animation effect before ajax call

I've watched several tutorials on how to load content without having to refresh the browser. I'm also using history pushState and popstate to update the url dynamically depending on what site that is displaying. However even if this code works, I would like to be able to

make som page transition animation effects
>
call the Ajax function
>
then make some fadeIn animation effects
. So far i've had no luck in trying to do so. I tried to read up on Ajax (beforeSend: function(){}), but the success function seems to execute before the (beforeSend) function. Is there anyone that could point me in the right direction, or tell me what i possibly am doing wrong? I'd appriciate it!

$(document).ready(function() {

var content, fetchAndInsert;

content = $('div#content');

// Fetches and inserts content into the container
fetchAndInsert = function(href) {
$.ajax({
url: 'http://localhost:8000/phpexample/content/' + href.split('/').pop(),
method: 'GET',
cache: false,
success: function(data) {
content.html(data);
}
});
};

// User goes back/forward
$(window).on('popstate', function() {
fetchAndInsert(location.pathname);
});

$('.buttonlink').click(function(){
var href = $(this).attr('href');

// Manipulate history
history.pushState(null, null, href);

// Fetch and insert content
fetchAndInsert(href);

return false;
});
});


Questions? Just ask!

Thanks beforehand!

/// E !

Answer

You need to use callbacks. The provided solutions will work, but not necessarily sequentially. $.animate() and $.ajax both run asynchronously. If unfamiliar with this term, here's a good intro: http://code.tutsplus.com/tutorials/event-based-programming-what-async-has-over-sync--net-30027

Here's what I might do:

   fetchAndInsert = function(href) {
       $('#some-element').animate({'opacity':'0.0'}, 1000, function () {
           $.ajax({
               url: 'http://localhost:8000/phpexample/content/' + href.split('/').pop(),
               method: 'GET',
               cache: false,
               success: function(data) {
                   content.html(data);
                   content.animate({'opacity':'1.0'}, 1000);
               }
           });
       });
    };

That will fade out whatever is currently in content, fetch the new data, replace what's currently in content, and then fade back in.