jQuery How do you get an image to fade in on load?
This thread seems unnecessarily controversial.
If you really want to solve this question correctly, using jQuery, please see the solution below.
The question is "jQuery How do you get an image to fade in on load?"
First, a quick note.
This is not a good candidate for $(document).ready...
Why? Because the document is ready when the HTML DOM is loaded. The logo image will not be ready at this point - it may still be downloading in fact!
So to answer first the general question "jQuery How do you get an image to fade in on load?" - the image in this example has an id="logo" attribute:
$("#logo").bind("load", function () { $(this).fadeIn(); });
This does exactly what the question asks. When the image has loaded, it will fade in. If you change the source of the image, when the new source has loaded, it will fade in.
There is a comment about using window.onload alongside jQuery. This is perfectly possible. It works. It can be done. However, the window.onload event needs a particular bit of care. This is because if you use it more than once, you overwrite your previous events. Example (feel free to try it...).
function SaySomething(words) {
alert(words);
}
window.onload = function () { SaySomething("Hello"); };
window.onload = function () { SaySomething("Everyone"); };
window.onload = function () { SaySomething("Oh!"); };
Of course, you wouldn't have three onload events so close together in your code. You would most likely have a script that does something onload, and then add your window.onload handler to fade in your image - "why has my slide show stopped working!!?" - because of the window.onload problem.
One great feature of jQuery is that when you bind events using jQuery, they ALL get added.
So there you have it - the question has already been marked as answered, but the answer seems to be insufficient based on all the comments. I hope this helps anyone arriving from the world's search engines!
You have a syntax error on line 5:
$('#logo').hide();.fadeIn(3000);
Should be:
$('#logo').hide().fadeIn(3000);
Simply set the logo's style to display:hidden
and call fadeIn
, instead of first calling hide
:
$(document).ready(function() {
$('#logo').fadeIn("normal");
});
<img src="logo.jpg" style="display:none"/>