Search code examples
javascriptjqueryjquery-animatedelayappendto

jquery: how can I stop appendTo from happening instantly?


I have been googling and trying for the life of me to delay appendTo from happening instantly, so that I can do a nice fadeout first. Here, myObject is a link:

<a href="#">My Link</a>

And I would like to move it into an unordered list:

<div id="newDiv">
<ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
</ul>
</div>

By doing something like this:

myObject.fadeOut(300).appendTo('#newDiv ul').fadeIn(300);
myObject.wrap('<li></li>');

I know that appendTo isn't an animation object though, so it just happens instantly. So I tried putting the append as a callback to fadeOut:

myObject.fadeOut(300, myObject.appendTo('#newDiv')).fadeIn(300);
myObject.wrap('<li></li>');

Only now it not only happens instantly, the wrap no longer works. I've also tried using a setTimeout to delay the appending to no avail.


Solution

  • Try this:

    myObject.fadeOut(300, function() { $(this).appendTo('#newDiv ul').fadeIn(300) });
    

    By doing the "appendTo" in the callback from the fade, you can wait until the fade is done. All (as far as I know) the jQuery animation effects take callbacks like that.