views:

148

answers:

2

I have a simple javascript function that allows me to add an item to a list. Note that I use JQuery...

function prependListItem(listName, listItemHTML)
{
    //Shift down list items...
    $("#" + listName + " li:first").slideDown("slow");

    //Add new item to list...
    $(listItemHTML).prependTo("#" + listName)  
}

The 'listName' is simply an <ul> with some <li>'s.

The prepending works fine, but I can't get the slideDown effect to work. I would like the list items to slide down and the new item to then appear on top. Any ideas how to accomplish this? I'm still new to JQuery...

+1  A: 

Try:

$("<li>new item</li>").hide().prependTo("#" + listName).slideDown("slow");

In other words:

  • Create the new list item;
  • Hide it (so it's not visible when added to the list);
  • Add it to the top of the list; then
  • Slide it down. The other items will slide down.
cletus
+4  A: 

If you wanted it to be added and slide down at the same time do this:

function prependListItem(listName, listItemHTML){
    $(listItemHTML).hide().prependTo('#' + listName).slideDown('slow');
}

To truly do exactly what you described (slide down, then fade in), you would need something like this:

function prependListItem(listName, listItemHTML){
    $(listItemHTML)
        .hide()
        .css('opacity',0.0)
        .prependTo('#' + listName)
        .slideDown('slow')
        .animate({opacity: 1.0})
}
Doug Neiner
Fantastic, thanks! I assume slideDown makes the item visible again? (un-hides it?)
willem
Yes, it will animate it in from a hidden state. The important thing is to hide it before prepending it so there is no flicker (appear then disappear).
Doug Neiner
@dcneiner: you can skip the nested callback with just `.slideDown('slow').animate({opacity: 1.0})`. The jQuery queues up animations for you by default.
Crescent Fresh
Excellent point @Crescent Fresh. Thanks!
Doug Neiner