Cwtch22
Cwtch22

Reputation: 79

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");
});
});

Upvotes: 1

Views: 176

Answers (4)

acarlon
acarlon

Reputation: 17282

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;        
}

Upvotes: 2

JustWe
JustWe

Reputation: 653

something like this here. wrap around with the settimeout function that I think would acheive it.

Delaying Javascript

Upvotes: -1

David Omid
David Omid

Reputation: 665

 setTimeout(function() {
          // Do something after 7 seconds
    }, 7000);

The advantage of setTimeout is you can cancel the delay at any time by using the clearTimeout function like this:

var timer = setTimeout(function() {
              // Do something after 7 seconds
        }, 7000);
window.clearTimeout(timer); // Cancel the timer. 

Upvotes: 2

pazcal
pazcal

Reputation: 938

With delay?

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

Upvotes: 3

Related Questions