0

I want an html element to be removed AFTER it is finished sliding up. But the remove is executed immediately.

$(document).ready(function() {

  $(':button').on('click', function() {
    $("body").prepend("<div class='messageBox'>dsds</div>");
    $(".messageBox").text('You Wot!').slideUp(0).slideDown("slow");

    setTimeout(function() {
      $(".messageBox").slideUp("slow"); //WAIT TILL FINISH THEN....
      $(".messageBox").remove();
    }, 2000);

  });

});
.messageBox {
  background: blue;
  color: #fff;
  padding: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>
Settings
</h1>
<h3>
bla bla bla bla
</h3>
<input type="button" value="SAVE" id="save" />
<input type="button" value="ERROR" id="saveE" />
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Sony ThePony
  • 315
  • 1
  • 2
  • 13

2 Answers2

1

Try using .queue() function (documentation):

$(".messageBox").slideUp("slow").queue(function() {
    var that = $(this);
    that.remove();
    that.dequeue();
});
.messageBox {
  height:200px;
  border:1px solid #d8d8d8;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<div class="messageBox">box</div>

Or, as mplungjan mentioned, execute the remove function inside the slideUp() callback function

kapantzak
  • 11,610
  • 4
  • 39
  • 61
1

Try this :

setTimeout(function() {

    $(".messageBox").slideUp("slow",function(){

    $(".messageBox").remove();

    })

 }, 2000);

Final code :

<!DOCTYPE html>
<html lang="en">
<head>
    
    <style>
        .messageBox {
            
            background: blue;
            color: #fff;
            padding: 20px;
        }
    </style>
    
</head>
    
    <body>
        
        <h1>Settings</h1>
        <h3>bla bla bla bla</h3>
        <input type="button" value="SAVE" id="save" />
        <input type="button" value="ERROR" id="saveE" />
        
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
        <script>
    
       $(document).ready(function() {
           
           $(':button').on('click', function() {
               
               $("body").prepend("<div class='messageBox'>dsds</div>");
               $(".messageBox").text('You Wot!').slideUp(0).slideDown("slow");
               
               setTimeout(function() {
                   $(".messageBox").slideUp("slow",function(){
                       $(".messageBox").remove();

                   })

               },2000);

           })
       })
       
    </script>
    </body>
</html>
Ehsan
  • 12,655
  • 3
  • 25
  • 44
  • You could have found this too I think... http://stackoverflow.com/questions/1084392/jquery-wait-till-end-of-slideup – mplungjan Sep 07 '16 at 14:46