...

View Full Version : Swap preloaded image using a variable



Martins
04-29-2009, 11:14 AM
Is it possible to preload an image assigning it a variable name and then swap it with an existing image by calling the variable ?

My attempt so far as follows does not find the image.

var banimg = new Image(760,60);
banimg.src = "pictures/new-image-name.jpg";

document.getElementById("existing-img-id").src = "banimg.src";

TinyScript
04-29-2009, 04:11 PM
that should work if you lose the quotes around banimg.src
document.getElementById("existing-img-id").src = banimg.src;

essential
05-10-2009, 05:37 PM
Simply attach this in your (x)HTML document's, using this as .js. This script will automatically preload all available images in your page.

/***********************************************
* Unobtrusive Image Preloader script - by CF-User: essential
* This notice MUST stay intact for use
***********************************************/
var preload, myImages;
var img, iLen, x, y;
var isImage = [ {
iSrc : [],
iPath : [] }];

preload = (function() {
myImages = function() {
if ( document.images ) {
img = ( document.getElementsByTagName ) ? document.getElementsByTagName("img") : document.images;
iLen = img.length;
try {
for ( x = 0; x < iLen; x++ ) {
isImage[0].iSrc[x] = new Image();
for ( y in isImage[0].iSrc ) {
isImage[0].iPath[y] = img[y].src;
}
isImage[0].iSrc[x].src = isImage[0].iPath[x];
img[x].src = isImage[0].iSrc[x].src;
} return true;
}
catch( e ) {
(( e.description ) ? alert( e.description ) : alert( e.message ));
}
} return false;
}; // Main Function
return {
myImages : myImages
};
}()); // Preloaded Images

window.onload = preload.myImages;



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum