views:

2586

answers:

8

Hi all, I have the following problem which i'm trying to solve with Javascript. I have a div with a backgroudn image specified in a css file, and i want my javascript to change that image periodically (let`s say every 5 secs). I know how to change that, the problem is that i have a set of images in a folder to choose from for the back image. so i need to be able to open the folder, read the filenames into an array, change the backg image of the div, sleep for 5 and change again.

Why am i not using php?well because i need to dynamically change the css and it's easier in javascript

why not asp? because i'm on linux hosting

Now i suck at javascript so bear with me !

+1  A: 

You can't read a folder's contents, neither on the server nor on the clientside.

What you can do is to read the folder's contents with the help of a serverside script, and load it to a JavaScript array while processing the page.

TFM
Thanks Aaaron, missed the negation in the first sentence.
TFM
+1  A: 

You cannot do any file IO using JavaScript mainly because of security reason, so anyway you have to create some back end service which will update you with an list of available files in your folder. You don't have to do it in a hard way, you can use AJAX to it smoothly and nicely

Artem Barger
So basically i have to toss this back and forth between php and javascript? any good links or tutorials on how to integrate the both of them?
Blackbird57
See my answer :)
altCognito
Yes, and see the answer of @altCognito ;0)
Artem Barger
A: 

You're still going to need php or asp to query the folder for files. Javascript will not be able to "remotely" inspect the file system.

You can do something like the following in jQuery:

$.ajax({
  url: 'getFolderAsArrayOfNames.php',
  dataType: 'json',
  success: function(data) {
    for(var i=0;i<data.length;i++) {
      // do what you need to do
    }
  });
});

And in your getFolderAsArrayOfNames.php, something like this:

echo "function "
     .$_GET['callback']
     ."() {return "
     .json_encode(scandir('somepath/*.jpg'))
     ."}";
altCognito
disclaimer: This code isn't exactly copy paste safe, but it's a soli d start.
altCognito
Why don't you simply output the JSON string, instead of making use of JSONP?
Ionuț G. Stan
Pretty much six of one, half dozen of the other. For one version you have to do an eval, for the other version it's done for you.
altCognito
YOU DO NOT NEED PHP OR ASP TO QUERY THE FOLDER, IF THE WEB SERVER CAN PROVIDE A DIRECTORY LISTING. However if PHP is ok to use then this looks like it will work.
system PAUSE
That's an interesting point, even if it is ALL-CAPS, but then of course you're doing screen scraping, which is a little hokey, but still, I suppose it's still a valid point.
altCognito
@altCognito: Sorry for shouting, hadn't had my coffee yet, and I'm a bit irked by false cries of "impossible". Server-side is preferable for a number of reasons (eg. logging, security) but it seems OP was asking for a JS-only solution, and one exists. Hokey, yeah, a bit.
system PAUSE
A: 

You must send the list of names along with the JavaScript and then iterate through it.

Aaron Digulla
+1  A: 

This would not be ideal but in the absence of server-side processing (which you really should be doing--either PHP or Rails or Perl or whatever your host supports), you could allow directory listing on your images folder. This has security implications.

Then loading e.g., http://mysite.com/rotatingImages should respond with a list of files. You could do this with AJAX, parse out the relevant hrefs, push them onto an array and render your rotating images in JS.

steamer25
+2  A: 

in your javascript, use an array like

var images = [ "image1.jpg", "image2.jpg", "image3.jpg" ];

function changeImage() {
    var image = document.getElementById("yourimage");
    image.src=$images[changeImage.imageNumber];
    changeImage.imageNumber = ++changeImage.imageNumber % images.length;

}
changeImage.imageNumber=0;

setInterval(changeImage,5000);

The values in the array should be generated by your php

Jonathan Fingland
A: 

A noted above, you can not access server's system from a client's browser (which is where JavaScript runs).

You have 3 possible solutions:

  1. Create the JavaScript file via some dynamic back-end (php or perl scripts are best for that). The main JavaScript function could still be static but the initialization of the array used by it (either as a snippet on the main HTML page or a separate .js imported file) would be a php/perl generated URL. A recent StackOverflow discussion of the topic is at link text

  2. Make an XMLHttpRequest (AJAX) call from your JavaScript to a separate service (basically a URL backed by - again - php/perl backend script) returning XML/JSON/your_data_format_of_choice list of files. This is probably a better solution if you expect/want/need to refresh a frequently-changing list of images, whereas a pre-built list of files in solution #1 is better suited when you don't care about list of files changing while the web page is loaded into the browser.

  3. An un-orthodox solution - if browsers you care about support animated background images (gif/png), just compile your set of images, especially if they are small sized, into an animated gif/png and use that as background.

DVK
+1  A: 
  • If you are using Apache as your web server, and
  • if you can configure it to provide a default directory listing for your images folder (use the appropriate options in httpd.conf and/or .htaccess), and
  • if you don't care that the list of images is available to everyone who visits your web site,

then you don't need PHP or any other server-side processing.

You can use XMLHttpRequest (or the jQuery ajax function, which is a nice wrapper) to get the listing for the folder. The response will be HTML and it will look something like this:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> 
<html> 
 <head> 
  <title>Index of /demo1/images</title> 
 </head> 
 <body> 
<h1>Index of /demo1/images</h1> 
<pre><img src="/icons/blank.gif" alt="Icon "> <a href="?C=N;O=D">Name</a>                    <a href="?C=M;O=A">Last modified</a>      <a href="?C=S;O=A">Size</a>  <a href="?C=D;O=A">Description</a><hr><img src="/icons/back.gif" alt="[DIR]"> <a href="/demo1">Parent Directory</a>                             -   
<img src="/icons/image2.gif" alt="[IMG]"> <a href="tree.gif">tree.gif</a>                17-Mar-2009 12:58  6.2K  
<img src="/icons/image2.gif" alt="[IMG]"> <a href="house.gif">house.gif</a>               17-Mar-2009 12:58  6.5K  
<img src="/icons/image2.gif" alt="[IMG]"> <a href="car.gif">car.gif</a>                 02-Mar-2009 15:37  8.4K  
<img src="/icons/image2.gif" alt="[IMG]"> <a href="elephant.jpg">elephant.jpg</a>            02-Mar-2009 15:37  3.4K  
<hr></pre> 
<address>Apache/2.0.63 (Unix) Server at zeppo Port 80</address> 
</body></html>

Since this output is pretty predictable, you might try parsing out the filenames using a JavaScript regular expression, but it's probably just as easy and more robust to create a hidden DIV on your page, put the HTML response into that DIV, and then use DOM methods to find <a href>s that are after <img> tags with an alt="[IMG]" attribute. Once again, using jQuery Selectors or similar helper methods available in other toolkits will make this DOM parsing pretty easy.

Once you have the URL of the new image (parsed from the href), you can set the new CSS background for your div with the .style.backgroundImage property.

system PAUSE