简体   繁体   中英

Detach and move element after completing animation

I have a list of items with a close button associated with each item. When clicked, animation plays, list slides up and the item is removed successfully .

$(document).on("click", ".close-button", function(e) { //removes with animation
    $(this).parent().animate({
        opacity: 0
    }, 250, function() {
        $(this).animate({
                marginBottom: 0
            }, 250)
            .children()
            .animate({
                padding: 0
            }, 250)
            .wrapInner("<div />")
            .children()
            .slideUp(250, function() {
                $(this).closest(".element").remove();
            });
    });
});

I attempted to modify the above piece of code so that instead of removing the item, I detach the item and move it to another view. I attempted this using the below code, to no avail. $(this).closest('.element').detach().prependTo('#diff-view').hide().slideDown(250)

Getting rid of the animations moves the element to a different view successfully.

$(document).on("click", ".close-button" ,function(e) { //detaches w/o animation
  $(this).closest('.element').detach().prependTo('#diff-view').hide().slideDown(250)
});

I want to keep the animations of course, but I just can't figure out how to detach instead of remove while keeping them in place. Any help would be greatly appreciated.

As you are animating parent this refers to the animated element. As result reference to close button is lost.

Store the reference of element of current element and the use later to target.

$(document).on("click", ".close-button", function (e) { 
    //Store the reference
    var $this= $(this);
    $(this).parent().animate({
        opacity: 0
    }, 250, function () {
        $(this).animate({
            marginBottom: 0
        }, 250)
        .children()
        .animate({
            padding: 0
        }, 250)
        .wrapInner("<div />")
        .children()
        .slideUp(250, function () {
            $this.closest('.element').prependTo('#diff-view').hide().slideDown(250)
        });
    }); 
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM