14

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

APAD1
  • 13,509
  • 8
  • 43
  • 72

7 Answers7

21

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

Exil
  • 311
  • 2
  • 11
  • 26
Can Rau
  • 3,130
  • 1
  • 23
  • 33
6

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

Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
4

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);
MrMacvos
  • 103
  • 2
  • 8
3

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
martincarlin87
  • 10,848
  • 24
  • 98
  • 145
1
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.

Flip Vernooij
  • 889
  • 6
  • 15
1

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.

Trikaldarshiii
  • 11,174
  • 16
  • 67
  • 95
0

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

$("<div>Your content</div>").hide().prependTo(".prependHere");
$(".prependHere:first-child").slideDown();
kravits88
  • 12,431
  • 1
  • 51
  • 53