Search code examples
jquerydelay

How to add a delay in JQuery Code


So the code below makes it so that an image fades in, how would I delay this by 7 seconds before the fade-in actually begins? Here's the code;

jQuery:

$(document).ready(function() {
$(".delayImg").each(function() {
    this.onload = function() {
        $(this).animate({opacity: 1}, 8000);
    };
    this.src = this.getAttribute("delayedSrc");
});
});

Solution

  • You can use either jquery delay() or setTimeout(). Here is a jsfiddle showing both.

    As David Omid already pointed out, the javascript timeout is more flexible, because you can cancel it. .delay() method is used for delaying between queued jQuery effects.

    HTML:

    <img id="delayImg1" class="delayImg" src="imgSource">
    <img id="delayImg2" class="delayImg" src="imgSource">
    

    Javscript:

    var m_delayTimer = null;
    var m_delayTime = 5000;
    function showImage()
    {
        $("#delayImg2").animate({opacity: 1}, 2000)
    }
    
    $(document).ready(function() {
        $("#delayImg1").each(function() {
            this.onload = function() {
               $(this).delay(m_delayTime).animate({opacity: 1}, 2000);
            };        
        });
        m_delayTimer = window.setTimeout(showImage,m_delayTime);
    });
    

    CSS:

    .delayImg
    {
        opacity:0;        
    }