Abishek
Abishek

Reputation: 11691

jquery animations when appending html

I am trying to create the fadeIn effect when prepending a <UL> using Jquery, but the animation effect never appears on the page. Am i doing a mistake in specifying the fadeIn effect?

This is how my code looks

<UL id="myUL">
   <LI> First Item <LI>
   <LI> Second Item <LI>
   <LI> Third Item <LI>
   <LI> Fourth Item <LI>
<UL>

The Jquery is as follows (on button click)

var liData = "<LI> A New Item </LI>";
$('#myUL').prepend(liData).fadeIn('slow');

Though the <LI> appears correctly on the page, i donot see the fadeIn effect on the page. Am i doing something wrong in binding the data and the effect on the item?

Upvotes: 5

Views: 14009

Answers (4)

Shef
Shef

Reputation: 45589

First, the item should be added by an event so you can notice it, not at the load time.

Second, the newly added list item should be by default hidden so it can be displayed with a fade-in effect.

Here is the code:

$('#add_item').click(function(e){
    e.preventDefault();
    var liData = '<LI style="display:none"> A New Item </LI>';
    $(liData)
        .prependTo('#myUL')
        .fadeIn('slow'); 
});

Here is a demo

Upvotes: 1

IOrlandoni
IOrlandoni

Reputation: 1828

Added the display:none style, so Its not visible as soon as you prepend it and somewhat inverted the jQuery line.

var liData = '<LI style="display:none"> A New Item </LI>';
$(liData).prependTo('#myUL').fadeIn('slow');

JSFiddle : http://jsfiddle.net/sPeHy/4/

Upvotes: 8

Ilia Choly
Ilia Choly

Reputation: 18557

try this

$('#myUL').prepend($("<LI> A New Item </LI>").hide().fadeIn('slow'));

fiddle: http://jsfiddle.net/sPeHy/3/

Upvotes: 0

Joseph Marikle
Joseph Marikle

Reputation: 78520

Demo

This should do it

$('#myUL').prepend(liData).find("li:first").hide().fadeIn('slow');

Basically you were selecting the ul and not the li. Also you need to hide it before you fade it in or it will just fade from 100% to 100%, and you will see nothing in effect.

Upvotes: 2

Related Questions