28

I'm trying to load #content of a url via AJAX using jQuery within #primary. It loads but doesn't fadeIn. What am I doing wrong?

$('.menu a').live('click', function(event) {
        var link = $(this).attr('href');
        $('#content').fadeOut('slow', function(){
            $('#primary').load(link+' #content', function(){
                $('#content').fadeIn('slow');
            });
        });
        return false;
    });

Many thanks for your help.

Gab
  • 2,216
  • 4
  • 34
  • 61

6 Answers6

38

Actually I was able to do it by applying the effect to the wrapper div instead...

$('#primary').fadeOut('slow', function(){
    $('#primary').load(link+' #content', function(){
        $('#primary').fadeIn('slow');
    });
});
Gab
  • 2,216
  • 4
  • 34
  • 61
10

Just this:

$('.element').load('file.html',function(){}).hide().fadeIn();

Or to add this behaviour as default in the load() function:

$.fn.load_=$.fn.load;
$.fn.load=function(){
    return $.fn.load_.apply(this,arguments).hide().fadeIn();
}
Brynner Ferreira
  • 1,527
  • 1
  • 21
  • 21
3

You can also use .load() in fading effect like this

$("#container").fadeOut("slow").load('data.html').fadeIn('slow');

Vijaysinh Parmar
  • 897
  • 1
  • 15
  • 19
3

When using load() jQuery internally uses html() to updated your element. This means you can't apply any animation to it, as you're just updating the innerHTML property of the element.

Instead you'll need to write your own AJAX request to get the new HTML, put it in the element, then call fadeIn().

$('.menu a').live('click', function(event) {
    var link = $(this).attr('href');

    $('#content').fadeOut('slow', function() {
        $.get(
            link +' #content', 
            function(data) {
                $("#primary").html(data).fadeIn('slow');
            }, 
            "html"
        );
    });
    return false;
});

I used get() here, but you could just as easily use post() or ajax().

Also, just to note, live() has been deprecated. You should instead use delegate() or, if you are using jQuery 1.7+, on().

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • It becomings really slow. It seems to be reloading every js scripts of the destination page. I also use the jQuery address plugin and it seems to break it somehow. – Gab Feb 18 '12 at 01:12
2

I've found doing something like this works well...

$('#Div').fadeOut(0).fadeIn().load('foo.blah.html');

badsector
  • 51
  • 5
0

This is the best way to fade in/out it naturaly, first you hide your container then you load your page in this container (it will be loaded but hidden) then just use the Jquery function .fadeIn() and it will unhide it adding the special effect.

$(".myClass").click(function () 
{
    $("#Container").hide();
    $("#Container").load("magasin.html");
    $("#Container").fadeIn(); 
});
Khan Laoji
  • 19
  • 4