Question

I'm trying to prepend a div and load content in it with AJAX but the div remains empty

$('#primary').fadeOut('slow', function(){
        $('#primary').prepend('<div id="content"/>', function(){
            $('#content').load(link+' #content', function(){
                $('#primary').fadeIn('slow');
            });
        });
    });
Was it helpful?

Solution

prepend doesn't have a callback, it's an immediate change. Try this:

$('#primary').fadeOut('slow', function(){
    $('<div id="content"/>').prependTo('#primary')
         .load(link+' #content', function(){
            $('#primary').fadeIn('slow');
        });
});

OTHER TIPS

The .prepend method doesn't take a callback, because it isn't asynchronous.

You can pass a function as the first argument, but it isn't as useful for prepending to only one element.

Here's your code fixed.

$('#primary').fadeOut('slow', function(){
    var content = $('<div id="content"/>'),
        primary = $(this);
    primary.prepend( content );
    content.load(link + ' #content', function(){
        primary.fadeIn('slow');
    });
});

Try something like the following:

$('#primary').fadeOut('slow', function(){
    var primary = this;
    $('<div id="content"/>')
        .prependTo(primary)
        .load(link+' #content', function(){
            $(primary).fadeIn('slow');
        });
    });
});

The .prepend() method doesn't take a callback. I've used .prependTo() instead (which also doesn't take a callback) because it keeps the context so then the .load() call can be chained.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top