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.
The jQuery animate() method is used to create custom animations. Syntax: $(selector).animate({params},speed,callback); The required params parameter defines the CSS properties to be animated.
The animate() is an inbuilt method in jQuery which is used to change the state of the element with CSS style. This method can also be used to change the CSS property to create the animated effect for the selected element. Syntax: (selector).
The jQuery library provides several techniques for adding animation to a web page. These include simple, standard animations that are frequently used, and the ability to craft sophisticated custom effects.
jQuery can be several times slower than CSS when talking about animations. CSS animations and transitions have the advantage of being hardware accelerated by the GPU, which is really good in moving pixels.
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);
Personally, I would grab jQuery UI Sortable functionality and trigger the events on ajax success. take a look at this documentation and let me know if you like the idea.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With