Pure JavaScript fadeout then load - javascript

I have a fairly simple jQuery snippet that fades out an element then loads an external PHP page via AJAX after a button is clicked, and I'm trying to do the same thing using Javascript, so I can avoid using jQuery at all.
jQuery:
$(document).on("click", "#button", function () {
$("#image").fadeOut(580, function () {
$("#image-wrapper").load("loader.php");
});
return false;
});
Javascript:
document.getElementById("button").addEventListener("click", function () {
var xhr = new XMLHttpRequest();
xhr.onload = function () {
if (xhr.status >= 200 && xhr.status < 300) {
document.getElementById("image").classList.add("fade--out");
document.getElementById("image-wrapper").innerHTML = xhr.responseText;
console.log("Success");
} else {
console.log('Error');
}
};
xhr.open('GET', 'loader.php');
xhr.send();
});
And some CSS:
.fade--out {
opacity: 0;
}
#image {
transition: opacity 480ms ease 0s;
}
So far I have written that but I can only get the XMLHttpRequest to work ok but I can't seem to get the image element to fade out before loading the PHP file. How can I get the image div to fade out then load the PHP file inside the imaga-wrapper div?

See comments:
document.addEventListener("click", function (evt) {
// Because of event delegation, we need to check to see
// if the source of the event was the button
if(evt.target.id === "button"){
// Add a class to the image that changes the opacity to fully
// transparent, but because of the default image styling, a
// CSS transition will do that over the course of 480 milliseconds.
document.getElementById("image").classList.add("fade--out");
// Once that is done, call the supplied function
requestAnimationFrame(function(){
// AJAX Call here
});
}
});
.fade--out {
opacity: 0;
}
#image {
transition: opacity 480ms ease 0s;
}

Related

Why does the 2nd script prevent the 1st script from redirecting and how can I fix it?

Everything works properly EXCEPT the redirection. If I remove the 2nd script the redirection works. Is there something I need to do to get both working?
<script>
function check_frame() {
if( top === self ) { // not in a frame
location.href = "https://xyz.any"; // either the frameset or an error.
}
}
</script>
<script>
function check_frame() {
if( top !== self ) { // in a frame
document.body.classList.add('framed');
}
}
</script>
<body onLoad="check_frame()">
</body>
<style>
body {
opacity: 0;
transition: opacity 2s ease-in;
}
body.framed {
opacity: 1;
}
</style>
You don't need (actually, it does not make sense) two definitions of the same function. Just wrap up in an single implementation, like this:
function check_frame() {
if( top === self ) { // not in a frame
location.href = "https://xyz.any"; // either the frameset or an error.
}
else {
document.body.classList.add('framed');
}
}

How to Fade Out an element using Javascript

I have a loading page that I used javascript to make. I would like to be able to fade-out the loading page as the index.html fades in. I understand this can easily be done with jQuery, but would like to not use jQuery since I have yet to use it on this site. I understand this may be a common question, but I have not been able to tailor other answers to my solution since most use jQuery.
I am thinking to edit the opacity of the loading element onReady. Or could I do this with simple CSS?
Javascript:
function onReady(callback) {
var intervalID = window.setInterval(checkReady, 1000);
function checkReady() {
if (document.getElementsByTagName('body')[0] !== undefined) {
window.clearInterval(intervalID);
callback.call(this);
}
}
}
function show(id, value) {
document.getElementById(id).style.display = value ? 'block' : 'none';
}
onReady(function () {
show('page', true);
show('loading', false);
});
HTML:
<div id="loading">
<div class="logo">
Logo
</div>
<span class="loading-center-cross"></span>
<h3>Loading...</h3>
</div>
<div id="page">
.....
</div>
I expect for the loading screen to fade to the index.html as previously described. Thanks for all the help!
You can do this with CSS, using something like the following:
function onReady(callback) {
var intervalID = window.setInterval(checkReady, 1000);
function checkReady() {
if (document.getElementsByTagName('body')[0] !== undefined) {
window.clearInterval(intervalID);
callback.call(this);
}
}
}
function show(id, value) {
document.getElementById(id).classList.toggle('fade-in-out', value);
}
onReady(function () {
show('page', true);
show('loading', false);
});
And have the following CSS:
#page,
#loading {
transition: opacity 1s;
}
.fade-in-out {
opacity: 0;
pointer-events: none;
}
That way, the show() function will toggle a class of fade-in-out based on value, and there will be a transition to 'fade' the div in and out, with an addition of pointer-events: none to make the div non-interactive whist transitioning.

Translate jQuery click(), hide() and fadeIn() to native JS

So, I'm trying hard to speed up my page (by avoiding some requests) and wonder if anyone knows how to keep the following code working without having to load the whole JQuery library:
$("#div1").click(function () {
$("#div2).hide();
$("#div3").fadeIn();
})
Ofcourse this code needs a JQuery library to work, but it's heavier than my page itself.
Is there a way,somewhere, to just select the code needed from the library and insert it inline (in my html)?
Thank You,
CSS3 #keyframes is a clean way to do what you want without jQuery. Have a look at this thread, which has a demo. It actually runs smoother than jQuery's fadeIn.
Here's an example using CSS for the fade and plain Javascript for triggering the changes:
document.getElementById('div1').onmousedown = function() {
addClass('div2', 'hide');
addClass('div3', 'show');
}
function addClass(id, className) {
var el = document.getElementById(id);
if (el.classList)
el.classList.add(className);
else
el.className += ' ' + className;
}
#div2.hide {
display: none;
}
#div3 {
opacity: 0;
transition: 0.3s opacity ease;
}
#div3.show {
opacity: 1;
}
<div id="div1">div1</div>
<div id="div2">div2</div>
<div id="div3">div3</div>
If you aren't set on using jQuery you could just use normal JS, something along these lines:
document.getElementById('div1').onclick(function() {
document.getElementById('div2').style.visibility = 'hidden';
document.getElementById('div3').style.visibility = 'visible';
});
disclaimer there are better ways to do these DOM manipulations, this is an example!
The fadeIn function taken from here.
function fadeIn(el) {
el.style.opacity = 0;
var tick = function() {
el.style.opacity = +el.style.opacity + 0.01;
if (+el.style.opacity < 1) {
(window.requestAnimationFrame && requestAnimationFrame(tick)) || setTimeout(tick, 16)
}
};
tick();
}
document.getElementById("div1").onmousedown = function () {
document.getElementById("div2").style.display = 'none';
fadeIn(document.getElementById("div3"));
};
This only works on single selectors and not multiple elements at once, and it's not going to work for any other jQuery functions. For your situation it will allow a drop in replacement so you don't require an extra library.
$ = function(selector) {
return document.querySelector(selector);
}
HTMLElement.prototype.hide = function() {
this.style.visibility = "hidden";
this.style.opacity = 0;
}
HTMLElement.prototype.fadeIn = function() {
this.style.display = "block";
this.style.visibility = "visible";
this.style.opacity = 1;
}
For the fadeIn() animation you can add a CSS property to your element. This is set to 400ms just like jQuery's effect:
transition: opacity .4s ease;

How to put a default image if img tag is empty using jquery [duplicate]

I have a web page that includes a bunch of images. Sometimes the image isn't available, so a broken image is displayed in the client's browser.
How do I use jQuery to get the set of images, filter it to broken images then replace the src?
--I thought it would be easier to do this with jQuery, but it turned out much easier to just use a pure JavaScript solution, that is, the one provided by Prestaul.
Handle the onError event for the image to reassign its source using JavaScript:
function imgError(image) {
image.onerror = "";
image.src = "/images/noimage.gif";
return true;
}
<img src="image.png" onerror="imgError(this);"/>
Or without a JavaScript function:
<img src="image.png" onError="this.onerror=null;this.src='/images/noimage.gif';" />
The following compatibility table lists the browsers that support the error facility:
http://www.quirksmode.org/dom/events/error.html
I use the built in error handler:
$("img").error(function () {
$(this).unbind("error").attr("src", "broken.gif");
});
Edit: The error() method is deprecated in jquery 1.8 and higher. Instead, you should use .on("error") instead:
$("img").on("error", function () {
$(this).attr("src", "broken.gif");
});
In case someone like me, tries to attach the error event to a dynamic HTML img tag, I'd like to point out that, there is a catch:
Apparently img error events don't bubble in most browsers, contrary to what the standard says.
So, something like the following will not work:
$(document).on('error', 'img', function () { ... })
Hope this will be helpful to someone else. I wish I had seen this here in this thread. But, I didn't. So, I am adding it
Here is a standalone solution:
$(window).load(function() {
$('img').each(function() {
if ( !this.complete
|| typeof this.naturalWidth == "undefined"
|| this.naturalWidth == 0 ) {
// image was broken, replace with your new image
this.src = 'http://www.tranism.com/weblog/images/broken_ipod.gif';
}
});
});
I believe this is what you're after: jQuery.Preload
Here's the example code from the demo, you specify the loading and not found images and you're all set:
jQuery('#images img').preload({
placeholder:'placeholder.jpg',
notFound:'notfound.jpg'
});
$(window).bind('load', function() {
$('img').each(function() {
if( (typeof this.naturalWidth != "undefined" && this.naturalWidth == 0)
|| this.readyState == 'uninitialized' ) {
$(this).attr('src', 'missing.jpg');
}
});
});
Source: http://www.developria.com/2009/03/jquery-quickie---broken-images.html
While the OP was looking to replace the SRC, I'm sure many people hitting this question may only wish to hide the broken image, in which case this simple solution worked great for me.
Using Inline JavaScript:
<img src="img.jpg" onerror="this.style.display='none';" />
Using External JavaScript:
var images = document.querySelectorAll('img');
for (var i = 0; i < images.length; i++) {
images[i].onerror = function() {
this.style.display='none';
}
}
<img src='img.jpg' />
Using Modern External JavaScript:
document.querySelectorAll('img').forEach((img) => {
img.onerror = function() {
this.style.display = 'none';
}
});
<img src='img.jpg' />
See browser support for NodeList.forEach and arrow functions.
Here is a quick-and-dirty way to replace all the broken images, and there is no need to change the HTML code ;)
codepen example
$("img").each(function(){
var img = $(this);
var image = new Image();
image.src = $(img).attr("src");
var no_image = "https://dummyimage.com/100x100/7080b5/000000&text=No+image";
if (image.naturalWidth == 0 || image.readyState == 'uninitialized'){
$(img).unbind("error").attr("src", no_image).css({
height: $(img).css("height"),
width: $(img).css("width"),
});
}
});
This is a crappy technique, but it's pretty much guaranteed:
<img onerror="this.parentNode.removeChild(this);">
I couldn't find a script to suit my needs, so I made a recursive function to check for broken images and attempt to reload them every four seconds until they are fixed.
I limited it to 10 attempts as if it's not loaded by then the image might not be present on server and the function would enter an infinite loop. I am still testing though. Feel free to tweak it :)
var retries = 0;
$.imgReload = function() {
var loaded = 1;
$("img").each(function() {
if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
var src = $(this).attr("src");
var date = new Date();
$(this).attr("src", src + "?v=" + date.getTime()); //slightly change url to prevent loading from cache
loaded =0;
}
});
retries +=1;
if (retries < 10) { // If after 10 retries error images are not fixed maybe because they
// are not present on server, the recursion will break the loop
if (loaded == 0) {
setTimeout('$.imgReload()',4000); // I think 4 seconds is enough to load a small image (<50k) from a slow server
}
// All images have been loaded
else {
// alert("images loaded");
}
}
// If error images cannot be loaded after 10 retries
else {
// alert("recursion exceeded");
}
}
jQuery(document).ready(function() {
setTimeout('$.imgReload()',5000);
});
You can use GitHub's own fetch for this:
Frontend: https://github.com/github/fetch
or for Backend, a Node.js version: https://github.com/bitinn/node-fetch
fetch(url)
.then(function(res) {
if (res.status == '200') {
return image;
} else {
return placeholder;
}
}
Edit: This method is going to replace XHR and supposedly already has been in Chrome. To anyone reading this in the future, you may not need the aforementioned library included.
This is JavaScript, should be cross browser compatible, and delivers without the ugly markup onerror="":
var sPathToDefaultImg = 'http://cdn.sstatic.net/stackexchange/img/logos/so/so-icon.png',
validateImage = function( domImg ) {
oImg = new Image();
oImg.onerror = function() {
domImg.src = sPathToDefaultImg;
};
oImg.src = domImg.src;
},
aImg = document.getElementsByTagName( 'IMG' ),
i = aImg.length;
while ( i-- ) {
validateImage( aImg[i] );
}
CODEPEN:
This has been frustrating me for years. My CSS fix sets a background image on the img. When a dynamic image src doesn't load to the foreground, a placeholder is visible on the img's bg. This works if your images have a default size (e.g. height, min-height, width and/or min-width).
You'll see the broken image icon but it's an improvement. Tested down to IE9 successfully. iOS Safari and Chrome don't even show a broken icon.
.dynamicContainer img {
background: url('/images/placeholder.png');
background-size: contain;
}
Add a little animation to give src time to load without a background flicker. Chrome fades in the background smoothly but desktop Safari doesn't.
.dynamicContainer img {
background: url('/images/placeholder.png');
background-size: contain;
animation: fadein 1s;
}
#keyframes fadein {
0% { opacity: 0.0; }
50% { opacity: 0.5; }
100% { opacity: 1.0; }
}
.dynamicContainer img {
background: url('https://picsum.photos/id/237/200');
background-size: contain;
animation: fadein 1s;
}
#keyframes fadein {
0% {
opacity: 0.0;
}
50% {
opacity: 0.5;
}
100% {
opacity: 1.0;
}
}
img {
/* must define dimensions */
width: 200px;
height: 200px;
min-width: 200px;
min-height: 200px;
/* hides broken text */
color: transparent;
/* optional css below here */
display: block;
border: .2em solid black;
border-radius: 1em;
margin: 1em;
}
<div class="dynamicContainer">
<img src="https://picsum.photos/200" alt="Found image" />
<img src="https://picsumx.photos/200" alt="Not found image" />
</div>
If you have inserted your img with innerHTML, like: $("div").innerHTML = <img src="wrong-uri">, you can load another image if it fails doing, e.g, this:
<script>
function imgError(img) {
img.error="";
img.src="valid-uri";
}
</script>
<img src="wrong-uri" onerror="javascript:imgError(this)">
Why is javascript: _needed? Because scripts injected into the DOM via script tags in innerHTML are not run at the time they are injected, so you have to be explicit.
Better call using
jQuery(window).load(function(){
$.imgReload();
});
Because using document.ready doesn't necessary imply that images are loaded, only the HTML. Thus, there is no need for a delayed call.
CoffeeScript variant:
I made it to fix an issue with Turbolinks that causes the .error() method to get raised in Firefox sometimes even though the image is really there.
$("img").error ->
e = $(#).get 0
$(#).hide() if !$.browser.msie && (typeof this.naturalWidth == "undefined" || this.naturalWidth == 0)
By using Prestaul's answer, I added some checks and I prefer to use the jQuery way.
<img src="image1.png" onerror="imgError(this,1);"/>
<img src="image2.png" onerror="imgError(this,2);"/>
function imgError(image, type) {
if (typeof jQuery !== 'undefined') {
var imgWidth=$(image).attr("width");
var imgHeight=$(image).attr("height");
// Type 1 puts a placeholder image
// Type 2 hides img tag
if (type == 1) {
if (typeof imgWidth !== 'undefined' && typeof imgHeight !== 'undefined') {
$(image).attr("src", "http://lorempixel.com/" + imgWidth + "/" + imgHeight + "/");
} else {
$(image).attr("src", "http://lorempixel.com/200/200/");
}
} else if (type == 2) {
$(image).hide();
}
}
return true;
}
I found this post while looking at this other SO post. Below is a copy of the answer I gave there.
I know this is an old thread, but React has become popular and, perhaps, someone using React will come here looking for an answer to the same problem.
So, if you are using React, you can do something like the below, which was an answer original provided by Ben Alpert of the React team here
getInitialState: function(event) {
return {image: "http://example.com/primary_image.jpg"};
},
handleError: function(event) {
this.setState({image: "http://example.com/failover_image.jpg"});
},
render: function() {
return (
<img onError={this.handleError} src={src} />;
);
}
I created a fiddle to replace the broken image using "onerror" event.
This may help you.
//the placeholder image url
var defaultUrl = "url('https://sadasd/image02.png')";
$('div').each(function(index, item) {
var currentUrl = $(item).css("background-image").replace(/^url\(['"](.+)['"]\)/, '$1');
$('<img>', {
src: currentUrl
}).on("error", function(e) {
$this = $(this);
$this.css({
"background-image": defaultUrl
})
e.target.remove()
}.bind(this))
})
Here is an example using the HTML5 Image object wrapped by JQuery. Call the load function for the primary image URL and if that load causes an error, replace the src attribute of the image with a backup URL.
function loadImageUseBackupUrlOnError(imgId, primaryUrl, backupUrl) {
var $img = $('#' + imgId);
$(new Image()).load().error(function() {
$img.attr('src', backupUrl);
}).attr('src', primaryUrl)
}
<img id="myImage" src="primary-image-url"/>
<script>
loadImageUseBackupUrlOnError('myImage','primary-image-url','backup-image-url');
</script>
Pure JS.
My task was: if image 'bl-once.png' is empty -> insert the first one (that hasn't 404 status) image from array list (in current dir):
<img src="http://localhost:63342/GetImage/bl-once.png" width="200" onerror="replaceEmptyImage.insertImg(this)">
Maybe it needs to be improved, but:
var srcToInsertArr = ['empty1.png', 'empty2.png', 'needed.png', 'notActual.png']; // try to insert one by one img from this array
var path;
var imgNotFounded = true; // to mark when success
var replaceEmptyImage = {
insertImg: function (elem) {
if (srcToInsertArr.length == 0) { // if there are no more src to try return
return "no-image.png";
}
if(!/undefined/.test(elem.src)) { // remember path
path = elem.src.split("/").slice(0, -1).join("/"); // "http://localhost:63342/GetImage"
}
var url = path + "/" + srcToInsertArr[0];
srcToInsertArr.splice(0, 1); // tried 1 src
if(imgNotFounded){ // while not success
replaceEmptyImage.getImg(url, path, elem); // CALL GET IMAGE
}
},
getImg: function (src, path, elem) { // GET IMAGE
if (src && path && elem) { // src = "http://localhost:63342/GetImage/needed.png"
var pathArr = src.split("/"); // ["http:", "", "localhost:63342", "GetImage", "needed.png"]
var name = pathArr[pathArr.length - 1]; // "needed.png"
xhr = new XMLHttpRequest();
xhr.open('GET', src, true);
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.status == 200) {
elem.src = src; // insert correct src
imgNotFounded = false; // mark success
}
else {
console.log(name + " doesn't exist!");
elem.onerror();
}
}
}
}
};
So, it will insert correct 'needed.png' to my src or 'no-image.png' from current dir.
(window.jQuery || window.Zepto).fn.fallback = function (fallback) {
return this.one('error', function () {
var self = this;
this.src = (fallback || 'http://lorempixel.com/$width/$height').replace(
/\$(\w+)/g, function (m, t) { return self[t] || ''; }
);
});
};
You can pass a placeholder path and acces in it all properties from the failed image object via $*:
$('img').fallback('http://dummyimage.com/$widthx$height&text=$src');
http://jsfiddle.net/ARTsinn/Cu4Zn/
For React Developers:
<img
src={"https://urlto/yourimage.png"} // <--- If this image src fail to load, onError function will be called, where you can add placeholder image or any image you want to load
width={200}
alt={"Image"}
onError={(event) => {
event.target.onerror = "";
event.target.src = "anyplaceholderimageUrlorPath"
return true;
}}
/>
I am not sure if there is a better way, but I can think of a hack to get it - you could Ajax post to the img URL, and parse the response to see if the image actually came back. If it came back as a 404 or something, then swap out the img. Though I expect this to be quite slow.
I solved my problem with these two simple functions:
function imgExists(imgPath) {
var http = jQuery.ajax({
type:"HEAD",
url: imgPath,
async: false
});
return http.status != 404;
}
function handleImageError() {
var imgPath;
$('img').each(function() {
imgPath = $(this).attr('src');
if (!imgExists(imgPath)) {
$(this).attr('src', 'images/noimage.jpg');
}
});
}
jQuery 1.8
// If missing.png is missing, it is replaced by replacement.png
$( "img" )
.error(function() {
$( this ).attr( "src", "replacement.png" );
})
.attr( "src", "missing.png" );
jQuery 3
// If missing.png is missing, it is replaced by replacement.png
$( "img" )
.on("error", function() {
$( this ).attr( "src", "replacement.png" );
})
.attr( "src", "missing.png" );
reference
Sometimes using the error event is not feasible, e.g. because you're trying to do something on a page that’s already loaded, such as when you’re running code via the console, a bookmarklet, or a script loaded asynchronously. In that case, checking that img.naturalWidth and img.naturalHeight are 0 seems to do the trick.
For example, here's a snippet to reload all broken images from the console:
$$("img").forEach(img => {
if (!img.naturalWidth && !img.naturalHeight) {
img.src = img.src;
}
}
I think I have a more elegant way with event delegation and event capturing on window's error even when the backup image fail to load.
img {
width: 100px;
height: 100px;
}
<script>
window.addEventListener('error', windowErrorCb, {
capture: true
}, true)
function windowErrorCb(event) {
let target = event.target
let isImg = target.tagName.toLowerCase() === 'img'
if (isImg) {
imgErrorCb()
return
}
function imgErrorCb() {
let isImgErrorHandled = target.hasAttribute('data-src-error')
if (!isImgErrorHandled) {
target.setAttribute('data-src-error', 'handled')
target.src = 'backup.png'
} else {
//anything you want to do
console.log(target.alt, 'both origin and backup image fail to load!');
}
}
}
</script>
<img id="img" src="error1.png" alt="error1">
<img id="img" src="error2.png" alt="error2">
<img id="img" src="https://i.stack.imgur.com/ZXCE2.jpg" alt="avatar">
The point is :
Put the code in the head and executed as the first inline script. So, it will listen the errors happen after the script.
Use event capturing to catch the errors, especially for those events which don't bubble.
Use event delegation which avoids binding events on each image.
Give the error img element an attribute after giving them a backup.png to avoid disappearance of the backup.png and subsequent infinite loop like below:
img error->backup.png->error->backup.png->error->,,,,,
If the image cannot be loaded (for example, because it is not present at the supplied URL), image URL will be changed into default,
For more about .error()
$('img').on('error', function (e) {
$(this).attr('src', 'broken.png');
});
I got the same problem. This code works well on my case.
// Replace broken images by a default img
$('img').each(function(){
if($(this).attr('src') === ''){
this.src = '/default_feature_image.png';
}
});

Load Image and Fade In, but in sequential way

I'm trying to load my images and fade in. Its working. But lets suppose that I have 4 images. Right now, my script its working by loading the last image, not the first. How can I make my js load the first image, and just start loading the second after the first has been loaded?
Here's my code:
$(function(){
$("a").click(function(){
$("#load").load('load.html', function() {
$('#load img').hide();
alert($("#load img").length);
$('#load img').each( function(){
$(this).on('load', function () {
$(this).fadeIn();
});
});
});
return false;
});
});
See http://jsfiddle.net/5uNGR/15/
Try something where you are not trying to perform a fadeIn on each image as they load, but test the ok-ness of the next image in your animation queue each time ANY load event happens, then on the animation callback, see if the next one is ready. Here is a script that should work.
BTW, see http://www.sajithmr.me/javascript-check-an-image-is-loaded-or-not for more on image readiness testing.
$(function () {
// util fn to test if image loaded properly
var isImgLoadOk = function (img) {
if (!img.complete) { return false; }
if (typeof img.naturalWidth != "undefined" && img.naturalWidth == 0) {
return false;
}
return true;
};
$("a").on('click', function () {
$("#load").load('load.html', function () {
var imgs = $('#load img').hide(), //create image array and hide (chaining)
animIndex = 0, //position in the animation queue
isFading = false; //track state of whether an animation is in prog
// this is a load handler AND is called in the fadeIn callback if
// not at last image in the collection
var fadeNextImg = function () {
// make sure a load event didn't happen in the middle of an animation
if (isFading) return;
// last image in animation queue?
var isLast = animIndex == imgs.length - 1;
// get the raw image out of the collection and test if it is loaded happily
var targetImage = imgs[animIndex];
if (isImgLoadOk(targetImage)) {
// jQuery-up the htmlImage
targetImage = $(targetImage);
// increment the queue
animIndex++;
// set animation state - this will ignore load events
isFading = true;
// fade in the img
targetImage.fadeIn('slow', function () {
isFading = false;
// test to see if next image is ready to load by
// recursively calling the parent fn
if (!isLast) fadeNextImg();
});
}
};
imgs.on('load', fadeNextImg);
});
return false;
});
});
Ron's solution is a little over-engineered IMO. If your intention is indeed to load all of the images before the animation starts, then you could do something similar to the following:
$(function(){
$("a").click(function(){
$("#load").load('load.html', function() {
$('#load img').hide(); // I would recommend using css to hide the image instead
alert($("#load img").length);
$("#load img").each(function(i, image) {
setTimeout(function() { // For each image, set increasingly large timeout before fadeIn
$(this).fadeIn();
}, 2000 * i);
});
});
return false;
});
});

Categories