Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New Coder
    Join Date
    Nov 2005
    Posts
    73
    Thanks
    18
    Thanked 0 Times in 0 Posts

    Swap preloaded image using a variable

    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";

  • #2
    Regular Coder
    Join Date
    Mar 2009
    Location
    Portland Oregon
    Posts
    690
    Thanks
    44
    Thanked 63 Times in 62 Posts
    that should work if you lose the quotes around banimg.src
    document.getElementById("existing-img-id").src = banimg.src;

  • #3
    New to the CF scene
    Join Date
    May 2009
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Simply attach this in your (x)HTML document's, using this as .js. This script will automatically preload all available images in your page.
    Code:
    /***********************************************
    * 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;


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •