Link to home
Start Free TrialLog in
Avatar of 2bears
2bearsFlag for New Zealand

asked on

How do I automatically populate a JavaScript Array

Hi Experts

The attached JavaScript code snippit is for a slideshow that is used to view images uploaded to the ~/uploads folder of the website by users. I run the script in the head of the MasterPage.master of an ASP website.

Question: Rather than hand coding each image filename, is there a way to automatically populate the "NewImg = new Array()" with the existing image filenames in the ~/uploads folder and automatically include any newly uploaded images filename also?

Kind regards
2bears
NewImg = new Array(
"uploads/01.jpg",
"uploads/02.jpg",
"uploads/03.jpg"
);
        var ImgNum = 0;
        var ImgLength = NewImg.length - 1;
 
        //Time delay between Slides in milliseconds
        var delay = 3000;
 
        var lock = false;
        var run;
        function chgImg(direction) {
            if (document.images) {
                ImgNum = ImgNum + direction;
                if (ImgNum > ImgLength) {
                    ImgNum = 0;
                }
                if (ImgNum < 0) {
                    ImgNum = ImgLength;
                }
                document.slideshow.src = NewImg[ImgNum];
            }
        }
 
        function auto() {
            if (lock == true) {
                lock = false;
                window.clearInterval(run);
            }
            else if (lock == false) {
                lock = true;
                run = setInterval("chgImg(1)", delay);
            }
        }

Open in new window

Avatar of Wayne Barron
Wayne Barron
Flag of United States of America image

here you go.

ASP & Access Database

http://ee.cffcs.com/Q_24481797/Q_24481797.asp
code
http://ee.cffcs.com/Q_24481797/Q_24481797.zip

Enjoy
Carrzkiss
It should use server side scripting. Javascript is client side scripting, I don't think a way to do it
Some information about Scripting.FileSystemObject should able to help you.
http://msdn.microsoft.com/en-us/library/2z9ffy99(VS.85).aspx
I love doing stuff like this. Since I get the list of files from the server I might not use javascript to create the images and instead make them server side... but what would be the fun in that?

So this example will get the images from a particular directory. It will always have the correct images even after an upload. It then puts a javascript array on the page with a list of those filenames. Then I went ahead and used javascript to create the images and put them into an element on the page.

Of course I could have been more extensive, but I think you have the image creation part already down. I just finished it off for testing purposes.

BTW, there is no way to do this with JavaScript, but I combined JS with ASP.NET (you didnt mention VB or C# so I picked). You could do the same thing with an AJAX call, but that's a moot point since you'd still have to write some .NET code :)

dday
*** ASPX PAGE ****
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default3.aspx.vb" Inherits="Default3" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
    <script type="text/javascript">
		//global variable called [files] is (array[string])
    
		function makeImgs()
		{
			var someWhereForImagesToGo = document.getElementById('someWhereForImagesToGo');
			
			for(i=0;i<files.length;i++)
			{
				var newImg = document.createElement('img');
				newImg.src = 'img/' + files[i];
				someWhereForImagesToGo.appendChild(newImg);
			}
		}
    
    </script>
    
    
</head>
<body onload="makeImgs();">
    <form id="form1" runat="server">
    <div id="someWhereForImagesToGo">
    
    </div>
    </form>
</body>
</html>
 
 
*** ASPX.VB PAGE ****
Imports System.Web.Script.Serialization
Imports System.IO
 
 
Partial Class Default3
    Inherits System.Web.UI.Page
 
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
 
        Dim files() As String = Directory.GetFiles(Server.MapPath("~/img"))
 
        For i As Integer = 0 To files.Length - 1
            Dim temp As String = files(i).Substring(files(i).LastIndexOf("\") + 1)
            files(i) = temp
        Next
 
 
        Dim json As New JavaScriptSerializer()
 
        Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "script", _
        "<script type=""text/javascript"">var files = " & json.Serialize(files) & ";</script>")
 
 
 
    End Sub
End Class

Open in new window

There should be a way to get more than 500 points for stuff like this ;)~
He posted to ASP Classic Zone, so once I came in and posted my code for this.
Is when I caught on that it was a .NET project. (I hate it when that happens :)  )

Anyway.
It is there for people that might find it useful.

And to [ddayx10]
I myself have to say thanks for the .NET code.
I am learning little bits of it myself, so this might turn out to be handy.

@2bears
Please, the next time that you post a question that is for .NET, please make sure that you do
Not include ASP Classic in on it.
Sometimes a Classic person will be able to help, but most of the time, you have
To wait longer then you should for a response.
At least you did add in the .NET to your, unlike some others that have posted to only
ASP Classic, and dealt with .NET.

Good Luck
Carrzkiss
Thanks Carrzkiss,

Nice to get a little pat on the back there. I know about the zones. I was a little disappointed its going to go down as javascript points for me...definitely I would rather this is ASP.NET Programming zone. Alas it is what it is.

dday
Yep.
Feel the same way.
I am classic ASP. and have a lot of points else where, even though I have provided asp code.

But, it is what ever the indivual needs to get done, so it is not a real big deal which zone that it is in.
As long as it is the proper zones, and if all possible, not the improper zones.
Of which I have brought up to EE Suggestions for seeing if it can be something that they can
Add in the future, and hopefully, it feel on good ears.

Take Care
Carrzkiss
<$.02>
"It should use server side scripting. Javascript is client side scripting..."

I use JavaScript on the client AND the server. Been doing it for a decade with no problems. I use IIS, so if you use something else, YMMV.
</$.02>
Avatar of 2bears

ASKER

Hi Carrzkiss and ddayx10
Thank you for your comprehensive replies. Sorry for posting to the wrong zones. Being pretty new to web programming I am still trying to understand the uses and roles of all the different web technologies. I start to understand the difference between ASP and ASP.NET now.
 The post from Car Thanks for the heads up :)
Carzkiss - I was somewhat confused by your code. Bit beyond my present skill level. Appologies to you Carrzkiss that I wasn't clearer with my question/platform - .
ddayx10 - I can understand the nature of your  solution ok but have trouble getting it to run in my app. (I have added some details below)
I got it running in its own website, except that it just showed all of the images at once.
Some notes re: My site. - I am using VB code behind pages.
1. I am using a MasterPage.master with asp:ContentPlaceHolders. id="ContentPlaceHolder3" as the "someWhereForImagesToGo"
2. On the Slideshow.aspx page I have the corresponding asp:Content ID...with an asp:Image ID placeholder nested inside.
3. The image folder is called ~/uploads (I think you used ~/img in the ASPX.VB PAGE code)
When I run the Slideshow page on my site the page loads with just an image place holder  (red box with X) in place of an image?
I also get a debug error - 'null' is null or not an object for this line of code in the function makeImgs() - someWhereForImagesToGo.appendChild(newImg);
 
 Kind regards 2bears
ASKER CERTIFIED SOLUTION
Avatar of Member_2_4913559
Member_2_4913559
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of 2bears

ASKER

Hi ddayx10.
Thank you for the detailed feedback and code examples. As well as gaining a solution to my question, I have also gained a much clearer understanding of the processes involved. Again, many thanks for the extended answer - kind regards 2bears