Question

So I understand there are many free image rotators, etc, out there using things like jQuery. My issue however, is it there a way to dynamically update the image rotator without refreshing the site page?

So basically you are displaying ten images then 1 hour later you have a script delete the old images add ten new images and a new xml file, do you need to do a refresh of the page? Or does the script always dynamically check the xml file, so you don't have to do a refresh.

p.s. it doesn't have to be in jQuery, could be HTML5 or the likes - I just want to be able to add and remove images from a folder, and have the rotator automatically update to use what's in the folder

Was it helpful?

Solution

I think it's best, if at all possible, to operate on the gallery without doing anything that might make it necessary to re-initialise it. The approach below seeks to achieve this aim by replacing the gallery images without replacing the img nodes themselves.

First, let's assume that the server-side code is up and working and returns, by whatever means, json that when decoded is equivalent to:

[
    "images/aaa.jpg",
    "images/bbb.jpg",
    "images/ccc.jpg",
    "images/ddd.jpg",
    "images/eee.jpg",
    etc.
]

Then:

$(function(){
    var $galleryImgs = $('#myGallery img');//gallery img nodes in a jQuery wrapper.
    var updateGallery = function() {
        $.ajax({
            url: 'getImageUrls.php', //or whatever
            data: {
                n: $galleryImgs.length //specify how many new image urls to fetch
            },
            dataType: 'json',
            success: function(data) {
                $.each(data, function(i, url) {
                    if($galleryImgs[i]) { //safety
                        $galleryImgs[i].src = url; //replace each gallery image in turn
                    }
                });
            }
        });
    };
    var galleryInterval = setInterval(updateGallery, 60*60*1000);//60*60*1000 for one hour; 30*60*1000 for half an hour
});

Thus, the gallery plugin will (hopefully) continue its rotation blissfully unaware that it's images have been changed. Some gallery plugins may be more amenable to this than others - experimentation necessary.

OTHER TIPS

As far as deleting and replacing files goes, you'd have to do that server side. You didn't mention a server language, so I suggest opening that up in a different question. Once you have that figured out, you can have your script poll the server for updates using ajax.

The query would look (something) like this:

 refreshShow = function() {
    $.ajax({
      url: 'imagefeed.json',
      dataType: 'json',
      type: 'post',
      data: {
        gallery: 'homeGallery'
      },
      success: function(data) {
        $('#homeGallery img').remove();
        $.each(data, function(i, image){
          $('#homeGallery').append(
            $('<img />').attr('href', image.path)
          )
        });
      }
    });
  };

Then your poll:

$(function(){
  setTimeout(function(){ refreshShow() }, 30000); //polls every 30 seconds for updates
});

Where a JSON feed would feed up some paths, maybe captions as well. You can find a whole bunch of questions on SO on creating JSON output in different languages. Keep in mind this is example code, and most slideshows are slightly more complex than this.

I assume, that the images in the folder have different names, so you may need to provide a URL, which you can poll to get the new file names, possibly like so:

http://example.com/imagenames

which returns json like this:

{
   images: ["i1.jpg", "i1.jpg", "i1.jpg", "i1.jpg", "i1.jpg"],
   version: 12
}

you can then frequently make ajax requests to that url, see if the version number is bumped and then replace the images in your image carousel. if you don't find one that lets you change the images dynamically, it should be pretty straight forward to write.

Here is one that sort of does that, you would only need to add auto-rotation: http://sorgalla.com/projects/jcarousel/examples/dynamic_flickr_api.html

Something like that could be accomplished through the use of a Server Side Language and Ajax. You didn't mention one, so I'll just go with PHP for the example, but the concept would pretty much be:

A) Start the rotator and load the images in the folder.

B) Use setTimeout(); to create a function that will use Ajax to call a PHP page that checks the directory, and returns a json of the images names in the directory that was checked.

C) Remove the rotator's current images and then repopulate it with the new information from the JSON.

An example would be:

[PHP]

$listOfImages = new array();

foreach( glob("/uploads/*.jpg") as $file ){
    array_push( $listOfImages, $file ); // gets an array of all the jpgs in the uploads directory
}
return json_encode( $listOfImages );

[jQuery]

<script type='text/javascript'>


    $(function($){
        var slider = new Slider(); //Pseudo-class for a slider
        setTimeout(function(){

           $.ajax({
             url:"update-slider-with-images.php",
             type:"post",
             dataType:"json",
             success:function(data){

               slider.clearAllImages(); //pseudo function to remove images from slider

               var images = JSON.parse( data );
               for(image in images){

                  slider.addImage( image ); //Psuedo function to add image to the rotation queue

               }

               slider.slide(); // Pseudo function to start the slider

            }

         });

        },300000); // check every 6 minutes

    });

</script>

That probably isn't everything you'd need, as you would need to create the slider class or reimplement that code in my example some other way, but it should be enough to get yourself started, provided that you know PHP. If you don't, I wouldn't think it's too hard to convert that to something else. I know Rails can handle filesystem stuff, and I'm sure ASP.Net can too.

Python Pyramid Example

I've already got an implementation of this up and working but I just don't have the images auto changing. I use an ajax request to

/basic_stats/graph.png?graph.type=IMAGE

where /basic_stats/graph.png is just a route I have configured to a specific view. Your image slider isn't going to care if you are passing arguments in the image link so long as the route returns the png or jpg that it's expecting. In my case I have an automated process that runs stats in the background and then stores the images to a Redis layer which the view for /basic_stats/graph.png? is configured to poll against. Then I just query the request.params['some_key_value'] and return an image as a response object. Then you don't have to do any ajax magic at all, just generate the right response object.

From __init__.py

config.add_route('ImageSlider', '/images/ImageSlider.png')

From views.py

@view_config(route_name='ImageSlider')
def ImageSlider(request):
    imgData = None
    if 'graph.type' in request.params:
        if request.params['image.name'] == 'ImageSlider1':
            r_server = redis.Redis('127.0.0.1')
            imgDataObj = r_server.get('ImageSlider1')
            del r_server
            imgData = pickle.loads(imgDataObj)
        elif request.params['image.name'] == 'ImageSlider2':
            r_server = redis.Redis('127.0.0.1')
            imgDataObj = r_server.get('ImageSlider2')
            del r_server
            imgData = pickle.loads(imgDataObj)
    return Response(body_file=imgData, content_type='image/png')

This example uses Redis to store the serialized image data but you could pretty easily load files from the FS with PIL ex

imgData = Image.open("/images/ImageSlider1.png")

You can now have the view respond with any images you want at those particular locations. Then just pass your image locations as such to your slider

Links for your slider

src="/images/ImageSlider.png?image.name=ImageSlider1"
src="/images/ImageSlider.png?image.name=ImageSlider2"

And just have your view adjust what image it responds with dynamically. Redis allows you to timeout your keys and have an external process repopulate the keys on listen to provide the new images to your webserver. Note that this probably won't scale as your shifting image data around, but for an internal application for basic stats reporting, which is what I use it for it's great, and seamlessly fast. I haven't load tested it to see what the upper limits are but we aren't going to have very many concurrent users.

Regardless of what framework you're working with though, this example should be an option to accomplish your task.

I imagine chaining view render calls in Backbone.js to alter image src during arbitrary update might also work but I haven't gotten very far down the Backbone.js rabbit hole yet and that concept is likely limited to Backbone.js.

Redis
Pyramid

I have a simple jQuery method you might be interested in.

The Image Rotator used in the example is JW Image Rotator which uses an external file in XSPF, RSS and ASX tags format.

It could also just be a plain and simple xml text file that the downloadable demo provides. You might consider using Flicker, and then accessing those RSS Feeds to streamline the playlists instead.


For the first issue you mentioned, updating a Image Rotator without refreshing the webpage is shown in the Demo via a simple setTimeout. It reloads either the same playlist.xml file which as been previously updated or uses a different playlist file.


To address your second issue, the playlist.xml files makes things easy when it reloads itself at the specified time since it will automatically force updating the contents that you have in your images folder (if not using RSS URL feeds for example).

Whenever you over-write the files, for example 01.jpg to 10.jpg, then during the Reload Event it will grab the new files thanks to the JW Image Rotator retrieving them.

This means no time-stamps or other hacks to force the Reload. To take it a step further, you can have a array of playlists that can by automatically cycled to have a fully automated process.


There's a lot of comments in the DEMO and a few console log messages to explain what's going on so that you can adapt the Demo's methods to any other Image Rotator or image plugin out there.


Here's a DEMO on jsFiddle that is the tutorial version.

This DEMO on jsFiddle contains no comments or console, so you can see the code cleanly.

Here is a pastebin of the tutorial version that is downloadable.

To try this DEMO locally, you'll need the open source JW Image Rotator, currently at v3.18 which now has the JW watermark but v3.17 doesn't have that... it's zipped HERE and it includes all source files including .fla Flash files.

The DEMO also contains a link to the JW Image Rotator JavaScript API commands that aren't even used... but are readily available to customize things even further!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top