Reputation: 889
I have the following code to animate a dynamic div up and down. The idea is that there could be any number of divs that need to be moved up and down the stack, swapping positions with the divs above and below. Once in their new position, I need to be able to catch that new re-odered position. The following code works, once, but once a lower div moves up and a upper moves down (swap spots) to the new positions, they stop working. How can I set this up so that they will continue to traverse up the stack, swapping the one immediately above or below as they go? I also need to know the new positions once finished to update the database. Ive been looking everywhere but can't seem to find how to do this. Any help would be much appreciated.
$('.editUp', this).click(function() {
thisRowHt = $(this).parents('.rowCont').outerHeight();
upperRowHt = $(this).parents('.rowCont').prev().outerHeight();
$(this).parents('.rowCont').animate({'top': '-=' + thisRowHt + 'px'});
$(this).parents('.rowCont').prev().animate({'top': '+=' + upperRowHt + 'px'});
return false;
});
$('.editDown', this).click(function() {
thisRowHt = $(this).parents('.rowCont').outerHeight();
lowerRowHt = $(this).parents('.rowCont').next().outerHeight();
$(this).parents('.rowCont').animate({'top': '+=' + lowerRowHt + 'px'});
$(this).parents('.rowCont').next().animate({'top': '-=' + thisRowHt + 'px'});
return false;
});
Upvotes: 0
Views: 384
Reputation: 529
You should swap the elements in the DOM also, because when you animate the HTML elements, they just change theirs place on the screen.
I have completed your script:
$('.editUp', this).click(function() {
var this_rowCont = $(this).parents('.rowCont');
var prev_rowCont = $(this).parents('.rowCont').prev();
// if this is the first element, it returns
if (prev_rowCont.length != 1){return false;}
thisRowHt = this_rowCont.outerHeight();
upperRowHt = prev_rowCont.outerHeight();
this_rowCont.animate({'top': '-=' + thisRowHt + 'px'});
prev_rowCont.animate({'top': '+=' + upperRowHt + 'px'}, function(){
// this is a callback function which is called, when the animation ends
// This swap this and previous element in the DOM
this_rowCont.insertBefore(prev_rowCont);
this_rowCont.css("top", 0);
prev_rowCont.css("top", 0);
});
return false;
});
$('.editDown', this).click(function() {
var this_rowCont = $(this).parents('.rowCont');
var next_rowCont = $(this).parents('.rowCont').next();
// if this is the last element, it returns
if (next_rowCont.length != 1){return false;}
thisRowHt = this_rowCont.outerHeight();
lowerRowHt = next_rowCont.outerHeight();
this_rowCont.animate({'top': '+=' + lowerRowHt + 'px'});
next_rowCont.animate({'top': '-=' + thisRowHt + 'px'}, function(){
// This swap this and next element in the DOM
next_rowCont.insertBefore(this_rowCont);
this_rowCont.css("top", 0);
next_rowCont.css("top", 0);
});
return false;
});
You can see it in action here: Animate div up and down
Upvotes: 1