list item move up & down
list item move up & down with animation
by Zhang Xuexiang
HTML
<span id="span-1">Contents of SPAN 1 [<a class="move-up"><b>Up</b></a>/<a class="move-down"><b>Down</b></a>]</span>
<span id="span-2">Contents of SPAN 2 [<a class="move-up"><b>Up</b></a>/<a class="move-down"><b>Down</b></a>]</span>
<span id="span-3">Contents of SPAN 3 [<a class="move-up"><b>Up</b></a>/<a class="move-down"><b>Down</b></a>]</span>
<span id="span-4">Contents of SPAN 4 [<a class="move-up"><b>Up</b></a>/<a class="move-down"><b>Down</b></a>]</span>
<span id="span-5">Contents of SPAN 5 [<a class="move-up"><b>Up</b></a>/<a class="move-down"><b>Down</b></a>]</span>
CSS
a {
display: inline-block;
text-align: center;
width: 50px;
}
span {
cursor: pointer;
display: block;
}
JavaScript
$(document).ready(function() {
$('.move-up').click(function() {
if ($(this).prev())
/* $(this).parent().insertBefore($(this).parent().prev()); */
animatedMove($(this).parent(), $(this).parent().prev(), 2)
});
$('.move-down').click(function() {
if ($(this).next())
/* $(this).parent().insertAfter($(this).parent().next()) */
animatedMove($(this).parent(), $(this).parent().next(), 1)
});
});
function animatedMove($fstElem, $scdElem, dirflag) {
var fstdir, scddir;
// up
if (dirflag == 2) {
fstdir = '-';
scddir = '';
} else if (dirflag == 1) {
// down
fstdir = '';
scddir = '-';
}
$fstElem.css({
transform: 'translateY(' + fstdir + $scdElem.height() + 'px)',
transition: 'transform 0.4s'
})
$scdElem.css({
transform: 'translateY(' + scddir + $fstElem.height() + 'px)',
transition: 'transform 0.4s'
})
setTimeout(function() {
$fstElem.css({
transform: 'none',
transition: 'unset'
})
$scdElem.css({
transform: 'none',
transition: 'unset'
})
if (dirflag == 2) {
$fstElem.after($scdElem)
} else if (dirflag == 1) {
$fstElem.before($scdElem)
}
cb && cb($fstElem)
}, 500)
}