Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 751
willem Avatar asked Dec 05 '09 07:12

willem


3 Answers

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})
}
like image 126
Doug Neiner Avatar answered Sep 17 '22 13:09

Doug Neiner


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.
like image 37
cletus Avatar answered Sep 20 '22 13:09

cletus


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

like image 44
Chetan Ankola Avatar answered Sep 17 '22 13:09

Chetan Ankola