Created
June 9, 2013 16:02
-
-
Save minch/5744056 to your computer and use it in GitHub Desktop.
Animate a list of elements: move (slide) element to the top
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// http://jsfiddle.net/uNv8C/ | |
// https://forrst.com/posts/Animated_list_item_reordering_in_jQuery-RR1 | |
$(document).ready(function() { | |
$('li').click(function() { | |
// the clicked LI | |
var clicked = $(this); | |
// all the LIs above the clicked one | |
var previousAll = clicked.prevAll(); | |
// only proceed if it's not already on top (no previous siblings) | |
if(previousAll.length > 0) { | |
// top LI | |
var top = $(previousAll[previousAll.length - 1]); | |
// immediately previous LI | |
var previous = $(previousAll[0]); | |
// how far up do we need to move the clicked LI? | |
var moveUp = clicked.attr('offsetTop') - top.attr('offsetTop'); | |
// how far down do we need to move the previous siblings? | |
var moveDown = (clicked.offset().top + clicked.outerHeight()) - (previous.offset().top + previous.outerHeight()); | |
// let's move stuff | |
clicked.css('position', 'relative'); | |
previousAll.css('position', 'relative'); | |
clicked.animate({'top': -moveUp}); | |
previousAll.animate({'top': moveDown}, {complete: function() { | |
// rearrange the DOM and restore positioning when we're done moving | |
clicked.parent().prepend(clicked); | |
clicked.css({'position': 'static', 'top': 0}); | |
previousAll.css({'position': 'static', 'top': 0}); | |
}}); | |
} | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment