jQuery: image fade in

Hi there I’ve set up for individual images to be faded in once they are loaded:


.fadein {display:none;}


<script type="text/javascript" src="jquery-1.3.2.js"></script>

<script type="text/javascript">                                         


<img class="fadein" src="image.jpg">

The whole thing works. I don’t really know JS, so I’d like to ask a couple of questions.

Question 1
But no images show up when JS is switched off. Is there any way to integrate the initial no-display thing from the CSS into the JS, so that the image displays when JS is switched off?

Question 2
Having several images like this on a page (up to 25), how could I make the images start fading in at slightly different times? Fading in one after the other would take too long, but starting at slightly different times and overlapping the fade-in would be perfect. (hope it’s clear what I mean).

Many thanks.

Whoops, I screwed up the brackets. It should be:

setTimeout(function() { $(this).fadeIn(); }, floor(Math.random()*500) );

Thanks for your reply, ScallioXTX.

I’ve tried your suggestion with of the random timeout. However, I can’t seem to get it to work (and Dreamweaver suggests that there is something wrong in this line:

setTimeout(function() { $(this).fadeIn(); , floor(Math.random()*500); });


Sure, ditch the CSS so everything is visible by default, and than change the jQuery code to:


You could add a random timeout such that some images will appear sooner than others. Like this:

		setTimeout(function() { $(this).fadeIn(); , floor(Math.random()*500); });

That will cause each image to show somewhere between 0 and 500 milliseconds (half a second) after it’s ready.

PS. Please note that .ready() is not the correct tool for the job, you’d better use .load()
Note that .load() can be buggy, so take care about what’s said in the info box here: http://api.jquery.com/load-event/

I’ve got one result myself in answer to question 1.

However, it took me a while to work out that the script has to be at the end of the document, not at the beginning.

<script type="text/javascript">                                         $(".fadein").hide();

Still question 2 remaining.