Sergi Sergi - 2 months ago 11
jQuery Question

setTimeout before function code

In this case, how can I execute a timeout before the fadeOut occurs? (Right where the comment is).

HTML

<button id="button"> Button </button>

<h1 id="one"> Test</h1>


CSS

#one {display:none;}


Javascript

$(document).ready(function(){
$("#button").click(function(){

$("#one").fadeIn('slow', (function(){
/* SetTimoeout */
$("#one").fadeOut('slow');

}));
})
});

Answer

Try this :

$(document).ready(function(){

    $("#button").click(function(){

    $("#one").fadeIn('slow', function(){

        $("#one").delay(3000).fadeOut('slow');

       })
    })
})

Final code :

<!DOCTYPE html>
<html lang="en">
<head>
    <style>
        
        #one {
            display: none;
        }
        
    </style>
</head>
    <body>
        
        <button id="button"> Button </button>
        <h1 id="one"> Test</h1>
        
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
        <script>
            
    $(document).ready(function(){

        $("#button").click(function(){

        $("#one").fadeIn('slow', function(){

            $("#one").delay(3000).fadeOut('slow');

           })
        })
    })
        
        </script>
    </body>
</html>