1

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");
});
});
asked Jan 13, 2014 at 20:38
2
  • 2
    api.jquery.com/delay Commented Jan 13, 2014 at 20:40
  • 1
    Try searching first next time: api.jquery.com/?s=delay. The jQuery docs are very helpful. Commented Jan 13, 2014 at 20:41

4 Answers 4

3

With delay?

$(document).ready(function() {
 $(".delayImg").each(function() {
 this.onload = function() {
 $(this).delay(7000).animate({opacity: 1}, 8000);
 };
 this.src = this.getAttribute("delayedSrc");
 });
});
answered Jan 13, 2014 at 20:40
Sign up to request clarification or add additional context in comments.

Comments

2

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; 
}
answered Jan 13, 2014 at 21:00

Comments

2
 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. 
answered Jan 13, 2014 at 20:41

1 Comment

Where would I place this code? In which part of the jQuery? Thanks!:)
-1

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

Delaying Javascript

answered Jan 13, 2014 at 20:43

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.