Using jQuery to re-order and animate list items?

Grim... picture Grim... · Nov 14, 2011 · Viewed 15.6k times · Source

So, I've got a list of items, something like:

<ul id="listHolder">
    <li id="l1">List item 1</li>
    <li id="l2">List item 2</li>
    <li id="l3">List item 3</li>

etc. An ajax call is being fired periodically, and I may need to re-order the list (by making one of the lower items become the first one in the list). That's easy to do just by changing the HTML of #listHolder, but I would like to animate it so the appropriate item moves up the page to the right place, and the others move down.

I've got no idea where to start =/

NB. It doesn't have to be a list: a div or any other element would be fine.

Answer

Grim... picture Grim... · Nov 14, 2011

Okay, I've done it - it was simpler than I imagined.

http://jsfiddle.net/Vyhph/

Note that if you click more than one list object inside of a second, everything goes wrong. You could easily stop this but it won't be an issue for me.

$("li").live("click", function() {
    var $myLi = $(this);
    var $myUl = $(this).parent();
    var listHeight = $myUl.innerHeight();
    var elemHeight = $myLi.height();
    var elemTop = $myLi.position().top;
    var moveUp = listHeight - (listHeight - elemTop);
    var moveDown = elemHeight;
    var liId = $myLi.attr("id");
    var enough = false;
    var liHtml = $myLi.outerHTML();

    $("li").each(function() {
        if ($(this).attr("id") == liId) {
            return false;
        }
        $(this).animate({
            "top": '+=' + moveDown
        }, 1000);
    });

    $myLi.animate({
        "top": '-=' + moveUp
    }, 1000, function() {
        $myLi.remove();
        var oldHtml = $myUl.html();
        $myUl.html(liHtml + oldHtml);
        $myUl.children("li").attr("style", "");
    });
});

(function($) {
    $.fn.outerHTML = function() {
        return $(this).clone().wrap('<div></div>').parent().html();
    }
})(jQuery);