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.
Page 1 of 2 12 LastLast
Results 1 to 15 of 21
  1. #1
    New Coder
    Join Date
    Jul 2005
    Posts
    23
    Thanks
    0
    Thanked 0 Times in 0 Posts

    How to call array images from <img src=” ”> ?

    Problem:
    There are X number of images in a folder. I want to have xhtml/css code that does NOT need to be modified when the image file name changes.

    Thus, <img src=”image[0]” /> (or whatever the name/code needs to be here), and all further images on the page (i.e. - <img src=”image[1]” />) must not have to be edited. Instead, I want to edit a separate image.js file stored in folder ‘media’ at the root of my site.

    Question:
    How does one call those images from within the img tag?

    Note: I do NOT want to preload these images and therefore have created an array in the images.js file.

    Code:
    image = new Array();
    image[0] ='../images/dog.jpg'
    image[1] ='../images/car.jpg'
    image[2] ='../images/home.jpg'
    image[3] ='../images/girl.jpg'
    image[4] ='../images/boy.jpg'
    image[5] ='../images/cookies.jpg'
    image[6] ='../images/plate.jpg'
    image[7] ='../images/santa.jpg'
    image[8] ='../images/bunny.jpg'
    image[9] ='../images/turkey.jpg'
    image[10] ='../images/presents.jpg'
    image[11] ='../images/food.jpg'
    image[12] ='../images/airplane.jpg'
    index = Math.floor(Math.random() * image.length);

    Question2:
    How would the solution differ if the image source were being passed to a swapImage function, i.e.- onmousedown="MM_swapImage('target','','images/dog.jpg',1)" ?

  • #2
    Senior Coder Arbitrator's Avatar
    Join Date
    Mar 2006
    Location
    Splendora, Texas, United States of America
    Posts
    3,302
    Thanks
    28
    Thanked 276 Times in 270 Posts
    Q1: Perhaps something like this? It creates a new image with the appropriate attributes and inserts it at the location in the document that you specify. All changes are made through the script rather than via XHTML or CSS. If you just need to change attributes of an existing image, well, that’s basically demonstrated below as well. If you used code like the below, you’d probably want to combine the four arrays.
    Code:
    for (var i = 0; i < image.length; i++) {
      var img =  document.createElement("img");
      img.alt = altText[i];
      img.width = width[i];
      img.height = height[i];
      img.src = image[i];
      element.appendChild(img);
      }
    For every complex problem, there is an answer that is clear, simple, and wrong.

  • #3
    New Coder
    Join Date
    Jul 2005
    Posts
    23
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Hmm, forgive my scripting ignorance. However, it doesn't look like this is what I'm looking for.

    I don't need to make changes the images themselves. I just want to change which images are used on the webpage by manually changing the image names in the image.js file, thereby leaving the xhtml code unchanged.

    I'll manually upload new image files then quickly edit the image array (in the image.js file) by manually changing out the names of the files loaded into the array (i.e.- cat.jpg instead of dog.jpg, & bicycle.jpg instead of car.jpg). Once done the img src tags just keeps calling image0, image1, image3 never knowing that they are now completely different images.

    The point is that it's easier to change img src file names in one short text file than going through an html doc and changing them.

  • #4
    Senior Coder Arbitrator's Avatar
    Join Date
    Mar 2006
    Location
    Splendora, Texas, United States of America
    Posts
    3,302
    Thanks
    28
    Thanked 276 Times in 270 Posts
    Based on your statements, it looks like the code that I provided is what you would need to do what you describe. You say that “[you] don’t need to make changes to the images themselves” yet you want to swap the old images for new ones which does require changing the images themselves.

    Specifically, you need to change the image’s src attribute to point to the new image. As a consequence, you most likely then need to change the alt attribute (required in XHTML) which provides a textual alternative when the image fails to display. Lastly, if the images vary in size, you may want to indicate the new image’s dimensions explicitly so that (A) the page and images appear to load more quickly and (B) your layout isn’t negatively affected should the images fail to load; that requires altering the width and height attributes/properties of the image.

    The example script I provided loops through your array, creates new image elements with information drawn from that array, and then appends those image elements to the document source, thus resulting in them being rendered.

    My guess though is that you actually want to edit the XHTML file first, despite claims to the contrary. Basically, you want dummy image elements that have their intended src attribute value supplied via JavaScript. Thus:

    <img alt="" src="" onload="this.src = image[0];"/>

    However, that’s not semantic, results in nothing being displayed if the user has JavaScript disabled, results in clutter in the XHTML source, and is hardly necessary since the image can be both created and added to the document’s source via JavaScript alone. Note that “onload...” is in red because that code is invalid; you would need to associate the new image URIs via a method that isn’t inline, such as window.onload.

    Of course, I may have it all wrong due to lack of information; in that case, you need to provide more details to get the information that you seek.

    Personally, if you’re only doing this to save yourself some effort editing one document (I can only assume), this is kind of pointless since writing the script will require more effort, increase the document’s effective file size, increase the code that must be sifted through, and decrease document accessibility.
    Last edited by Arbitrator; 12-22-2006 at 01:25 AM. Reason: Experimentation with vB Code.
    For every complex problem, there is an answer that is clear, simple, and wrong.

  • #5
    New Coder
    Join Date
    Jul 2005
    Posts
    23
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Again, please forgive my coding ignorance. The goal has been to swap out images, with the size & alt being of little concern in this particular context. However, I see now that having them referenced as well would be beneficial.

    I'm still uncertain how to incorporate your suggested script since I'm used to seeing something like:
    function FuncName() {
    ..jscript stuff..
    }

    ...and then calling it from the xhtml via something like:
    onmousedown="FuncName('x','y','z',1)"

    My hope has been to write the xhtml in such a way that the img src references the image in the array directly so that the only editing that ever gets done is to the array script.

    ...since the image can be both created and added to the document’s source via JavaScript alone.
    Do you mean by something like this?
    <script>document.write("<img SRC="+"images/"+image[0]+"/>");</script>
    <script>document.write("<img SRC="+"images/"+image[1]+"/>");</script>
    <script>document.write("<img SRC="+"images/"+image[2]+"/>");</script>

    This solves one problem in that the xhtml never has to get edited, only the file containing the array definitions.

    However, two problems and one issue remain:
    1) How can id, class, alt and size attributes be included in the above img src tag?
    2) How can this be used when the image source is passed to another script? i.e.- onmousedown="MM_swapImage('target','','images/image01.jpg',1)"
    3) Is it possible to put the document.write line in an external script file and call it from the xhtml instead of having script tags in the xhtml itself?

    Thanks for you help and patience!

  • #6
    Senior Coder Arbitrator's Avatar
    Join Date
    Mar 2006
    Location
    Splendora, Texas, United States of America
    Posts
    3,302
    Thanks
    28
    Thanked 276 Times in 270 Posts
    Quote Originally Posted by lllusion View Post
    1) How can id, class, alt and size attributes be included in the above img src tag?
    Okay, you don’t seem to understand the explanations or to be very familiar with JavaScript, so here’s an example: http://jsg.byethost4.com/demos/CF 103490 Demo.html. The source is provided at the end of this post for reference purposes.

    Quote Originally Posted by lllusion View Post
    2) How can this be used when the image source is passed to another script? i.e.- onmousedown="MM_swapImage('target','','images/image01.jpg',1)"
    (A) Don’t use inline script for your roll‐overs. Move all of that to a script file. (B) Access the data as variables. You’ve already assigned the array containing the data to a variable so you can just access the array to get the information.

    Quote Originally Posted by lllusion View Post
    <script>document.write("<img SRC="+"images/"+image[0]+"/>");</script>
    <script>document.write("<img SRC="+"images/"+image[1]+"/>");</script>
    <script>document.write("<img SRC="+"images/"+image[2]+"/>");</script>

    3) Is it possible to put the document.write line in an external script file and call it from the xhtml instead of having script tags in the xhtml itself?
    Don’t use document.write(). It’s bad practice and it’s illegal in XHTML anyway. Additionally, all attribute names in XHTML are in lowercase, so “SRC” is invalid. Finally, script elements require type attributes.

    Code:
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
      <head>
    
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
        <meta name="Author" content="Patrick Garies"/>
        <title>CF 103490 Demo</title>
    
        <style type="text/css">
          * {
            margin: 0;
            }
          html, body, div {
            height: 100%;
            font: 25px "Palatino Linotype", Palatino, serif;
            text-align: center;
            }
          div {
            float: left;
            width: 33.3%;
            }
          *#middle {
            background-color: #222;
            color: white;
            }
          h1, img {
            display: block;
            margin: 1em auto;
            }
        </style>
    
        <script type="text/javascript">
          var images = new Array();
          images[0] = new Array("Article A", "article_a.png");
          images[1] = new Array("Article B", "article_b.png");
          images[2] = new Array("Article C", "article_c.png");
          images[3] = new Array("Article D", "article_d.png");
          images[4] = new Array("Article E", "article_e.png");
          images[5] = new Array("Article F", "article_f.png");
          window.onload = function() {
            for (var i = 0; i < images.length; i++) {
              var image = document.createElement("img");
              image.alt = images[i][0];
              image.width = "150";
              image.height = "150";
              image.src = images[i][1];
              var j = i;
              if (j > 2) j = i - 3;
              document.getElementsByTagName("div")[j].appendChild(image);
              }
            }
        </script>
    
      </head>
      <body>
    
        <div>
          <h1>Column 1</h1>
        </div>
        <div id="middle">
          <h1>Column 2</h1>
        </div>
        <div>
          <h1>Column 3</h1>
        </div>
    
      </body>
    </html>
    For every complex problem, there is an answer that is clear, simple, and wrong.

  • #7
    New Coder
    Join Date
    Jul 2005
    Posts
    23
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Thank you, Arbitrator.
    I apologize if I seem a little slow or dense. As you have surmised, I have zero JavaScript education. Your patience and extended explanations are appreciated.

    Let’s see if I understand what you’ve given me.

    (A) Don’t use inline script for your rollovers. Move all of that to a script file. (B) Access the data as variables. You’ve already assigned the array containing the data to a variable so you can just access the array to get the information.
    Ok, I didn’t make the connection between accessing as variables vs. inline scripting, which is “not semantic, can cause display problems, results in clutter, and unnecessary.”

    Looking at your new script:
    I included the width and height attributes in the same array using the following modification, which allows for variable width and height properties as you previously pointed out. I also have moved the script into an imgList.js file and referenced it from the xhtml header.

    Code:
    var images = new Array();
          images[0] = new Array("Article A", "g04/article_a.png", "150", "150");
          images[1] = new Array("Article B", "g04/article_b.png", "150", "150");
          images[2] = new Array("Article C", "g04/article_c.png", "150", "150");
          images[3] = new Array("Article D", "g04/article_d.png", "150", "150");
          images[4] = new Array("Article E", "g04/article_e.png", "150", "150");
          images[5] = new Array("Article F", "g04/article_f.png", "150", "150");
          window.onload = function() {
            for (var i = 0; i < images.length; i++) {
              var image = document.createElement("img");
              image.alt = images[i][0];
              image.src = images[i][1];
              image.width = images[i][2];
              image.height = images[i][3];
              var j = i;
              if (j > 2) j = i - 3;
              document.getElementsByTagName("div")[j].appendChild(image);
              }
           }
    Does this array pre-load all the images? The concern is that I don’t want the user to wait for 9 to 18 60KB images to load, but would rather have each one load as needed.

    Other things that I do not understand:
    1. It appeared, at first, that all the div tags were getting parsed from top to bottom, each getting a new img element. But when I but when I attempt to add more images to the array to display more images in each column there’s a scripting error.

    2. Likewise, when I create a six column layout only the first three columns get parsed unless the j > 2 is changed to j > 5 (or greater). And if j > 4 then column 3 gets two images while all the rest get 1. I’m really at a loss here.

    3. IIUC, in this example all div tags (well, the first X number based on the 'j >' statement will be given an img tag. What if only some of the divs should contain images? How can these specific areas be targeted?

    Thanks again for your help!

  • #8
    Senior Coder Arbitrator's Avatar
    Join Date
    Mar 2006
    Location
    Splendora, Texas, United States of America
    Posts
    3,302
    Thanks
    28
    Thanked 276 Times in 270 Posts
    Quote Originally Posted by lllusion View Post
    As you have surmised, I have zero JavaScript education.
    Then how is this supposed to make updating images easier than updating an XHTML source? You’ll either need to edit the source or learn JavaScript. A good place to start learning is here.

    Quote Originally Posted by lllusion View Post
    Ok, I didn’t make the connection between accessing as variables vs. inline scripting, which is “not semantic, can cause display problems, results in clutter, and unnecessary.”
    Putting parts of your scripts inline makes it harder to tell what your scripts are doing since all of the script data is not in one place. Part of it might be in the head of the document (embedded), part of it might be in the body (inline), and part of it might be in a separate *.js file (external). I simply meant to keep all of your script information in one place as opposed to your proposal of using something like an (inline) event attribute (onmousedown) coupled with a separate file. It makes it easier to maintain your scripts.

    Quote Originally Posted by lllusion View Post
    Does this array pre-load all the images? The concern is that I don’t want the user to wait for 9 to 18 60KB images to load, but would rather have each one load as needed.
    None of the images are preloaded; each image is called on‐demand. Specifically, each image begins loading once its added to the page via appendChild().

    Quote Originally Posted by lllusion View Post
    1. It appeared, at first, that all the div tags were getting parsed from top to bottom, each getting a new img element. But when I but when I attempt to add more images to the array to display more images in each column there’s a scripting error.

    2. Likewise, when I create a six column layout only the first three columns get parsed unless the j > 2 is changed to j > 5 (or greater). And if j > 4 then column 3 gets two images while all the rest get 1. I’m really at a loss here.
    That script is specifically designed to load exactly six images into exactly three div elements. It sends the images into div nodes 0, 1, and 2; after that point, “i” is greater than two, so the if statement is triggered and “i” has three subtracted from it, resulting in the images being sent into div nodes 0 (3−3), 1 (4−3), and 2 (5−3) again.

    The script is designed for that page. It’s a demo that shows you how to do (in general) what I was explaining. You’ll need to write your own script to suit your own page(s).

    Quote Originally Posted by lllusion View Post
    3. IIUC, in this example all div tags (well, the first X number based on the 'j >' statement will be given an img tag. What if only some of the divs should contain images? How can these specific areas be targeted?!
    Use precision reference methods or assign the elements you wish to insert the images into an id attribute so that you can use getElementById() to target them.
    For every complex problem, there is an answer that is clear, simple, and wrong.

  • #9
    New Coder
    Join Date
    Jul 2005
    Posts
    23
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by Arbitrator View Post
    Then how is this supposed to make updating images easier than updating an XHTML source? You’ll either need to edit the source or learn JavaScript. A good place to start learning is here.
    It's easier to open and change out image names in a short imgList.js file that has all the names of the images listed line by line at the top of the file than to scan through an xhtml file. This is especially true if it's not me who needs to replace the images but rather someone else who understands neither xhtml nor JavaScript.

    None of the images are preloaded; each image is called on demand. Specifically, each image begins loading once its added to the page via appendChild().
    You previously said that it was both bad practice and illegal to use document.write(). The only other options are then document.createElement() and Node.appendChild(), correct? (And for the sake of keeping script information together this should be done in a separate file or in the header.)

    That script is specifically designed to load exactly six images into exactly three div elements. ...
    Thanks for explaining.

    Use precision reference methods or assign the elements you wish to insert the images into an id attribute so that you can use getElementById() to target them.
    The getElementById() I understand now (bummer that there's no getElementByClass since that seems like it would make life much easier), but as far as how to write a script to do with it exactly what I want (i.e. createElement or appendChild), or FTM what precision reference methods are, I'll have to do a bunch more reading.

  • #10
    New Coder
    Join Date
    Jul 2005
    Posts
    23
    Thanks
    0
    Thanked 0 Times in 0 Posts
    ...And thanks for the link to "W3C DOM Compatibility - Core"

  • #11
    Senior Coder Arbitrator's Avatar
    Join Date
    Mar 2006
    Location
    Splendora, Texas, United States of America
    Posts
    3,302
    Thanks
    28
    Thanked 276 Times in 270 Posts
    Quote Originally Posted by lllusion View Post
    You previously said that it was both bad practice and illegal to use document.write(). The only other options are then document.createElement() and Node.appendChild(), correct? (And for the sake of keeping script information together this should be done in a separate file or in the header.)
    There are other methods of inserting elements such as insertBefore() which puts an element just before another element and replaceChild() which replaces a specific child element of some parent element. I believe there are also other specific methods for elements that have certain mandatory structures such as tables and select lists, but I haven’t experimented with those yet.

    Quote Originally Posted by lllusion View Post
    The getElementById() I understand now (bummer that there's no getElementByClass since that seems like it would make life much easier), but as far as how to write a script to do with it exactly what I want (i.e. createElement or appendChild), or FTM what precision reference methods are, I'll have to do a bunch more reading.
    You should be able to create a behavior that targets based upon class by looping through all of the elements and testing whether the value of their class attribute matches some predetermined value. If the value does, then some part of the script would be executed.

    You can also put all of the elements in a class (without assigning a class attribute) into a single container with a specific ID then loop through the elements in that container. You would use a reference like this:

    Code:
    document.getElementById(elementId).getElementsByTagName(elementName)
    For every complex problem, there is an answer that is clear, simple, and wrong.

  • #12
    New Coder
    Join Date
    Jul 2005
    Posts
    23
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by Arbitrator View Post
    You should be able to create a behavior that targets based upon class by looping through all of the elements and testing whether the value of their class attribute matches some predetermined value. If the value does, then some part of the script would be executed.
    Attempt #1: all the images end up under column 3 instead of one in each column. Why?
    Code:
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
    
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <meta name="Author" content="Patrick Garies" />
    
    <title>Load Images from Array</title>
    
    <style type="text/css">
    * {margin: 0; padding: 0; border: 0;}
    
    html, body, div {height: 100%; font: 25px "Palatino Linotype", Palatino, serif; text-align: center;}
    div {float: left; width: 33%;}
    
    *#middle {background-color: #222; color: white;}
    
    h1, img {display: block; margin: 1em auto;}
    
    #dummy {position: absolute; top: 300px; left: 300px; height: 20px; width: 100px; font-size: 14px; color: #000000; background-color: yellow; border: black dotted 1px;}
    </style>
    
    <script>
          var images = new Array();
          images[0] = new Array("Article A", "images/article_a.png");
          images[1] = new Array("Article B", "images/article_b.png");
          images[2] = new Array("Article C", "images/article_c.png");
          window.onload = function() {
            for (var i = 0; i < images.length; i++) {
              var image = document.createElement("img");
              image.alt = images[i][0];
              image.width = "150";
              image.height = "150";
              image.src = images[i][1];
              var timgs=document.getElementsByTagName('a')
      	for (var i_tem = 0; i_tem < timgs.length; i_tem++)
    	  if (timgs[i_tem].className=='thumbImage'){
    	  timgs[i_tem].appendChild(image);
    	  }
            }
          }
    </script>
    </head>
    
    <body>
    
    <div>
      <h1>Column 1</h1>
    	<a href="#" class="thumbImage"></a>
    </div>
    
    <div id="middle">
      <h1>Column 2</h1>
    	<a href="#" class="thumbImage"></a>
    </div>
    
    <div>
      <h1>Column 3</h1>
    	<a href="#" class="thumbImage"></a>
    </div>
    
    <div id="dummy">
      <a href="#">Dummy div.</a>
    </div>
    
    </body>
    </html>
    BTW, I realized that you used window.onload = function () instead of <body onload="demo();"> so that the xhtml would verify strict. This also keeps, as you have stated, the JavaScript out of the xhtml. However, can there be two different functions each utilizing the window.onload?

  • #13
    Banned
    Join Date
    Oct 2005
    Location
    I'm in GMT -5
    Posts
    314
    Thanks
    0
    Thanked 1 Time in 1 Post
    Illusion:

    Code:
    <script type="text/javascript">
    
    	var images =[];
          	images[0] = ["Article A", "images/article_a.png"];
          	images[1] = ["Article B", "images/article_b.png"];
          	images[2] = ["Article C", "images/article_c.png"];
      
    	function insertImages(){
            
    		var timgs = document.getElementsByTagName('a')
    		for (i=0; i<images.length; i++)
    			{
              		var image = document.createElement("img");
              		image.alt = images[i][0];
              		image.width = "150";
              		image.height = "150";
              		image.src = images[i][1];
    			timgs[i].className = "thumbImage";
    			timgs[i].appendChild(image);
    			}
          }  
    
    
     	function init(){
    
    		insertImages();
    		//nextFunction();
    
    	}
    
    	onload=init;
    
    </script>
    </head>

  • #14
    New Coder
    Join Date
    Jul 2005
    Posts
    23
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Thanks Ancora.

    How does timgs[i].className = "thumbImage"; do an 'if' for className = "thumbImage" ? It looks like it would set all 'a' tags to the class "thumbImage". (Just like timgs[i].appendChild(image) appends/creates an image element for all 'a' tags with className="thumbImage".) ??

    Thanks for the input on the function init() to load multiple functions onload.

  • #15
    Banned
    Join Date
    Oct 2005
    Location
    I'm in GMT -5
    Posts
    314
    Thanks
    0
    Thanked 1 Time in 1 Post
    Illusion:

    You're welcome, I appreciate your courtesy.
    My goodness, yes, that line is wrong.
    It should be:

    image.className = "thumbImage";

    But, obviously, you knew that already...


  •  
    Page 1 of 2 12 LastLast

    Posting Permissions

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