willem
willem

Reputation: 27027

Using jquery, how to I animate adding a new list item to a list?

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...

Upvotes: 8

Views: 10271

Answers (3)

Chetan Ankola
Chetan Ankola

Reputation: 7045

http://jsfiddle.net/eCpEL/13/

this should help

Using keyframe animation

.comefromtop {
    animation: comefromtop 0.5s;
}
.pushdown {
    animation: pushdown 0.5s;
}

@-webkit-keyframes comefromtop {
  0%   { opacity:0; -webkit-transform: translateY(-100%); }
  100% { opacity:1; -webkit-transform: translateY(0px);   }
}

@-webkit-keyframes pushdown {
  0%   { /*opacity:0;*/ -webkit-transform: translateY(-10%); }
  100% { /*opacity:1;*/ -webkit-transform: translateY(0);   }
}

And using a basic javascript

function add() {
    var val = $('#input').val();
    var item = $('<li></li>').addClass('comefromtop').attr('id',val).text(val);         $('#Trees').prepend(item).addClass('pushdown');
    setTimeout(function () {
        $('#Trees').removeClass('pushdown');
    }, 600);
}
$('.add').click(add);
$('#input').on('keypress',function (e) {
    if (e.keyCode === 13) {
        add();
    }
});

You can achieve godliness

Upvotes: 1

Doug Neiner
Doug Neiner

Reputation: 66211

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})
}

Upvotes: 23

cletus
cletus

Reputation: 625307

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.

Upvotes: 3

Related Questions