rhyhann
rhyhann

Reputation: 3

How can I prevent jQuery from loading a modified content before hiding the element?

When I want to change the content of an element, it works fine without effects, and does this behaviour with the effects:

  1. changes the content to the new one
  2. does the hiding effect, on the new content
  3. does the showing effect, still on the new content

Here is the code that is launched everytime I need to change the content:

function changePage(slug) {
  var content = $('#content');
  var title   = $('#name');
  $.getJSON('http://'+location.host+'/'+slug+'.json', function(data) {
    $('#main').fadeOut('slow');
    title.html(data.name);
    content.html(data.content);
    $('#main').fadeIn('slow');
  });
}

Here is the code that runs this function:

var app = new Sammy.Application(function() {with(this){
  get('#/', function() { with(this) {
    changePage('_home');
  }});
  get('#/:page', function() { with(this) {
    changePage(params['page']);
  }});
}});
$(function(){app.run();});

It's sammy, http://github.com/quirkey/sammy/ .

Thank you by advance for your help !

Upvotes: 0

Views: 292

Answers (2)

seanmonstar
seanmonstar

Reputation: 11444

fadeIn and fadeOut cause asynchronous animations, so Javascript continues executing further statements while those effects occur. So, it starts to fadeOut the element, and barely after its started, you change the content, and then call a fade in which I imagine it gets added to an effect chain.

fadeOut allows you to pass a callback function, which fires after the animation is complete. So you can do this:

function changePage(slug) {
  var content = $('#content');
  var title   = $('#name');
  $.getJSON('http://'+location.host+'/'+slug+'.json', function(data) {
    $('#main').fadeOut('slow', function() {
        title.html(data.name);
        content.html(data.content);
        $('#main').fadeIn('slow');
    });

  });
}

Upvotes: 0

REA_ANDREW
REA_ANDREW

Reputation: 10764

The fadeOut and the fadeIn function have a complete handler you need to use for example:

$.getJSON('http://'+location.host+'/'+slug+'.json', function(data) {
    $('#main').fadeOut('slow',function(){
    title.html(data.name);
    content.html(data.content);
    $('#main').fadeIn('slow');
    });
  });

Now once the fade out effect has finished it will execute the data switch over and fade back in!

Andrew

Upvotes: 2

Related Questions