Search code examples
javascriptjqueryhtmlfunctiondelay

Add delay in jquery function


I have created a small function in jquery. I want it to load after some delay in time. But I am unable to execute this code with delay. Here is the Jquery code below.

$(function(){
        $('.fade').delay(5000).show();
        $('.sboxa').delay(5000).show()
    })

Here is the html code below:

<div class="fade"></div> <div class="sboxa"></div>

Please help in this functionality. Thanks


Solution

  • To sequence animations you need to use callbacks in the show() method. Inside the callback you can use a setTimeout() to delay the showing of the next element.

    $(function(){
        $('.fade,.sboxa').hide();
      
        $('.fade').show(0, function() {
            setTimeout(function() {
                $('.sboxa').show();
            }, 2000);
        });
    });
    .fade {
      display: block;
      width: 50px;
      height: 50px;
      background: cornflowerblue;
    }
    
    .sboxa {
      display: block;
      width: 100px;
      height: 100px;
      background: blue;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="fade">fade</div>
    <div class="sboxa">sboxa</div>