Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Please Help with a "for - or - while" loop to add lines to an array 2

Status
Not open for further replies.

dakipi

Technical User
Joined
Feb 6, 2006
Messages
7
Location
US
Hello,

I have a slideshow script that has the following lines in the javascript:

var fadeimages=new Array()
fadeimages[0]=["images/1.jpg", "", ""]
fadeimages[1]=["images/2.jpg", "", ""]
fadeimages[2]=["images/3.jpg", "", ""]
--------------------------------------

I want to be able to use a loop, to create the array, with whatever number of lines as I need, to accomodate the number of images I have in the images directory .. ie:

Something like this ( Which Doesn't work .. because I have no idea what I am doing .. lol ?? )

var fadeimages=new Array()
for (i = 0; i <= 5; i++)
{
j=i+1
document.write("fadeimages[" + i + "]=[\"images/" + j + ".jpg\", \"\", \"\"]")
document.write("<br>")
}

????

Thank You

Joe
 
This will populate your array for you:
Code:
var fadeimages = new Array();
for (i = 0; i <= 5; i++) {
  fadeimages[fadeimages.length] = ["images/"+(i+1)+".jpg", "", ""];
}
End result is the same as:
Code:
var fadeimages = new Array();
fadeimages[0]=["images/1.jpg", "", ""];
fadeimages[1]=["images/2.jpg", "", ""];
fadeimages[2]=["images/3.jpg", "", ""];
fadeimages[3]=["images/4.jpg", "", ""];
fadeimages[4]=["images/5.jpg", "", ""];

Hope that helps,
Jeff

[tt]Jeff's Page @ Code Couch
[/tt]

What is Javascript? FAQ216-6094
 
Do you know ahead of time how many images are in the directory and are the images always going to be numerically sequential?

Adding items to the array or just creating the array all at once is easy but how do you intend to GET the names or number of images up front?

Can you run ASP code?
I put together a nice script that runs server-side to read in all of the file names in a folder, filter them for image types and return the list in a Javascript array.


Stamp out, eliminate and abolish redundancy!
 
BabyJeffy - Thank You :-)
That works perfectly.

As to the total number of images in the images directory .. how would I change this, to Automatically count the number of images in the images dir, and insert that number in the script?

ie here: for (i = 0; i <= ??
 
[tt]
var n=6; //some number determined by some method
var fadeimages=new Array();
for (var i=0;i<n;i++) {
fadeimages.push(["images/"+i+1+".jpg","",""]);
}
alert (fadeimages[2][0]); //illustration
[/tt]
 
hold up - what about push ?

var fadeimages = new Array();
for (i = 0; i <= 5; i++) {
fadeimages.push("images/"+(i+1)+".jpg", "", "");
}

 
hold up - what about push ?

var fadeimages = new Array();
for (i = 0; i <= 5; i++) {
fadeimages.push("images/"+(i+1)+".jpg");
}

 
it didn't like "push"

Another thing ...

How would I change the above, to have it insert the name of the image(s) instead of just a sequential numbering ..
ie: mypic.jpg and myotherpic.jpg , as opposed to 1.jpg and 2.jpg?
I think that made sense .. lol
 
You should really use server-side code to do your reading of the folder to get the filenames.
This code uses ASP and the FileSystemObject to read files, filter them for specified image extensions and load them into a javascript array.
The IUSR_machinename account must have permissions to access the FileSystemObject.

Code:
<html>
<head>
<%
  Dim fso
  Set fso = Server.CreateObject("Scripting.FileSystemObject")
  Dim rootFolder
  Set rootFolder = fso.GetFolder(Server.MapPath("/myfolder/images/"))
  Dim files
  Set files = rootFolder.Files
 
  ' Write the javascript header
  response.write "<SCR" & "IPT LANGUAGE=""JavaScript"">" & vbCrlf
  ' then declare the array
  response.write "var arrImages = new Array();" & vbCrlf
  outstr="arrImages = ["
 
  For Each file in files
    If file.Type = "GIF Image" OR file.type = "JPG Image" Then
      ' Store filename in Client Side Javascript array arrImages
      If cnt <> 0 then
        outstr = outstr & ","
      End if
      cnt=cnt+1
      outstr = outstr & "'" & file.Name & "'"
    End If
  Next
 
  outstr = outstr & "];" & vbCrLf
  response.write outstr
  ' write the script trailer...
  Response.Write "</SCR" & "IPT>" & vbCrlf
 
  Set files = Nothing
  Set rootFolder = Nothing
  Set fso = Nothing
%>
 
<script language="javascript">
for (var loop=0;loop<arrImages.length;loop++)
{
  document.write(arrImages[loop] + "<br>");
}
</script>
</head>
<body>
</body>
</html>

Stamp out, eliminate and abolish redundancy!
 
UGH!!

That is more complicated than I thought it might be ....

I will have the image names and a count stored in a MySQL database - Is there an easy way to import that number into the javascript?

Oh yeah .. Thank You All, for the help so far :-)
 
I think going to the database would be even more complex as it requires that you have a method of updating the names in the database every time you add new images.
Also, wouldnt you be using server-side code to go against the database to retrieve the names anyway?

The code above is not really complex, it just opens a filesystem object and begins reading filenames from the specified folder. If the filename extension is .gif or .jpg then it is added to a string. Once all filenames have been checked it does a single response.write to generate the javascript array with all of the names.

You can plug this code into your script with almost no modification except perhaps for the folder path of the images and the name of the array it will output to.

If you want to do it from a database you would just open up the recordset of image names and use a loop to build the string almost identically to the above method and write it to the browser. The benefit of the code above is that you never have to know how many files are there or what their names are. If a new file is added it is automatically shown the next time the page is loaded without the need for updating the code or database.



Stamp out, eliminate and abolish redundancy!
 
will this script work on a linux box ( LAMP )?

I tried it on my local box, and it didn't do anything useful .. lol
 
It is ASP. ASP will run on a linux box if you have added ASP support to the server. I am not familiar with them but there are a couple of ASP installs available for linux.

You could do something similar in PHP or CGI as well.
The FileSystemObject is I believe only a Microsoft object but there are comparable commands in PHP.

The only real drawback for using a database is that you have to update the database with any new filenames, remove old ones, etc. You could just about as easily add those names to the code though which is what you were trying to avoid.


Stamp out, eliminate and abolish redundancy!
 
understood..
I guess I failed to mention, that I would already be adding the information about the images, etc. to the database, under the member's account - so the only problem would be getting the count from the database, and importing it into the javascript - probably using PHP ???
 
That would probably be the best way to go then.
I am not terribly familiar with PHP yet so cannot give you specific examples but you should be able to find some good samples in the PHP forum.

In the code above I create a variable and put in the opening code tag.
Code:
  ' Write the javascript header
  response.write "<SCR" & "IPT LANGUAGE=""JavaScript"">" & vbCrlf
  ' then declare the array
  response.write "var arrImages = new Array();" & vbCrlf
  outstr="arrImages = ["
Then loop through the recordset adding each value to the outstr variable. I use a counter to test if I am at the first record so I know whether to add the comma before the new value. This is also where I test for the correct file type. If you use a database you do not need to do that test as you already know they are images.
Code:
  For Each file in files
    If file.Type = "GIF Image" OR file.type = "JPG Image" Then
      ' Store filename in Client Side Javascript array arrImages
      If cnt <> 0 then
        outstr = outstr & ","
      End if
      cnt=cnt+1
      outstr = outstr & "'" & file.Name & "'"
    End If
  Next
Then I add in the text to close off the array code, write that to the browser and then close the script tag.
Code:
  outstr = outstr & "];" & vbCrLf
  response.write outstr
  ' write the script trailer...
  Response.Write "</SCR" & "IPT>" & vbCrlf

You can use almost identically the same approach and substitute the recordset in place of the code reading from the folder.

Or, you can use PHP code to read thefilenames from the folder. Here is an example. You would have to modify it to output a javascript array rather than PHP as the example uses but you would do it almost identically to how I accomplished it in the code above.
Code:
<?php  
   $imgdir = '/Users/lixlpixel/Pictures/pics/'; // the directory, where your images are stored  
   $allowed_types = array('png','jpg','jpeg','gif'); // list of filetypes you want to show  
   $dimg = opendir($imgdir);  
   while($imgfile = readdir($dimg))  
   {  
    if(in_array(strtolower(substr($imgfile,-3)),$allowed_types))  
    {  
     $a_img[] = $imgfile;  
     sort($a_img);  
     reset ($a_img);  
    }   
   }  
   $totimg = count($a_img); // total image number  
   for($x=0; $x < $totimg; $x++)  
   {  
    $size = getimagesize($imgdir.'/'.$a_img[$x]);  
    // do whatever  
    $halfwidth = ceil($size[0]/2);  
    $halfheight = ceil($size[1]/2);  
    echo 'name: '.$a_img[$x].' width: '.$size[0].' height: '.$size[1].'<br />';  
   }  
?>

Post in the PHP forum, someone has probably already written code to do what you are looking for.


Stamp out, eliminate and abolish redundancy!
 
Thank You - You gave me the direction to go :-)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top