APAD1
APAD1

Reputation: 13666

Possible to animate jQuery prepend?

I am prepending some data to my page on a button click and instead of just populating immediately on the page, I was wondering if there is a way to animate the prepend() using slideToggle or CSS animation.

Here is my current script:

var data = $('.data').html();
var insert = '<div class="data-container">'+ data +'</div>';
$('button').click(function(){
    $('.data-container').remove();
    $('.initial').prepend(insert);
});

and a JSFiddle

Upvotes: 14

Views: 17095

Answers (7)

kravits88
kravits88

Reputation: 13049

I had to do in two lines to get a smooth slideDown animation:

$("<div>Your content</div>").hide().prependTo(".prependHere");
$(".prependHere:first-child").slideDown();

Upvotes: 0

MrMacvos
MrMacvos

Reputation: 103

You can animate prepend() or append() quite easy. Just pass the whole animated object as a parameter, like so:

$("#container").prepend( $(data).hide().delay(500).show('slow') );

If you like it more readable:

var object = $(data).hide().delay(500).show('slow');
$("#container").prepend(object);

Upvotes: 4

Can Rau
Can Rau

Reputation: 3819

This one liner works great for me, even without the clone()

I'm using it like so:

var elementToPrepend = "<div>Your content</div>";
$(elementToPrepend).hide().prependTo(".prependHere").fadeIn();

Edit: Proper one-liner would be:

$("<div>Your content</div>").hide().prependTo(".prependHere").fadeIn();

Source

Upvotes: 21

martincarlin87
martincarlin87

Reputation: 11042

Like this? http://jsfiddle.net/zR9fN/5/

CSS

/* add display:none; to keep it hidden after being prepended */
.data-container {
    display:none;
    ...
}

jQuery

....
$('.initial').prepend(insert);
$('.data-container').fadeIn('slow'); // fade in the prepended content that was hidden

Upvotes: 3

Mohit
Mohit

Reputation: 11314

You can simply animate before prepending. If you animate it before prepending it will appear with animation.

for example

childContainer.fadeIn(1000);
$(containerElement).prepend(childContainer);

Alternative to fadeIn you can use any animation.

Upvotes: 1

Arron
Arron

Reputation: 916

var data = $('.data').html();
var insert = '<div id="animationWrapper" style="height: 0"><div class="data-container">'+ data +'</div></div>';
$('button').click(function(){
    $('.data-container').remove();
    $('.initial').prepend(insert);
    jQuery('#animationWrapper').animate({height: '300px'}, 5000, function(){console.log('Yammie!')})
});

Please check the syntax, but this should be a start.

Upvotes: 1

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

You have to do something like this:

var data = $('.data').html();
var insert = '<div class="data-container">'+ data +'</div>';
$('button').click(function(){
    $('.data-container').remove();
    $('.initial').hide();
    $('.initial').prepend(insert);
    $('.initial').slideToggle();

});

FIDDLE UPDATED

Upvotes: 6

Related Questions