Sony ThePony Sony ThePony - 3 months ago 12
jQuery Question

Do next method once this one is complete

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" />




Answer

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>