Home > javascript, jquery > Circular Image Slide with jQuery

Circular Image Slide with jQuery


A friend of mine asked me to write a little script for him the other day that would do the following :

1. Slide a list of images from right to left across the screen.
2. When an image moves out of view on the left, it should get appended to the end of the list thus creating the illusion of a never ending or circular procession of images across the screen.
3. Display a “loader” image while the photographs are downloading.
4. You can view a demo of the end result here.

My first impression was that there’s almost certainly a jQuery plugin capable of doing this. Well if there is, I haven’t found it yet. While there are a myriad of “Slide” plugins available, and some come quite close, none could fulfill these requirements.

So I had to go and write my own little script. I haven’t converted the code to plugin form just yet as I need to look a few things up.

If you’d like to just jump straight in, here’s a zipped version of the demo.

First, the HTML:

<div id="slider">
<div id="imageloader">
			<img src="images/ajax-loader.gif" /></div>
<img src="images/sample1.jpg" />
		<img src="images/sample2.jpg" />
		<img src="images/sample3.jpg" />
		<img src="images/sample4.jpg" />
		<img src="images/sample5.jpg" /></div>

Nothing out of the ordinary here, just a div with a bunch of image tags. The only thing to note is the div’s “id”. The real magic happens in the JS and CSS. The pre-loader image is located inside a nested div with an id of “imageloader”. By default, our loader will be visible while our photographs are hidden.

That brings us to the CSS:

#slider {position: relative; overflow: hidden; height:155px;}
#slider img {position:absolute;	margin:0; display:none;}
#imageloader {position:relative; display:block; width: 100%; margin: 0px auto; text-align: center;}
#imageloader img { position:relative; top:70px; z-index:100; width:128px; height:15px; display:inline;}

Firstly, due to the nature of the script we have to make use of relative and absolute positioning. With that in mind, we first set our container div to relative positioning. This allows us to assign an absolute position to each child image, this is critical to the functioning of this script.

Next we set the overflow style to “hidden” – this makes sure that we don’t get ugly scroll-bars when images are moving outside of the containing div’s bounds.

We also need to set a fixed height for the container div. Failing to do so will result in the images not being displayed at all (due to the absolute positioning and overflow setting).

For the nested images, we want to set their initial display attribute to “none”. This is so they don’t display until our DOM is ready and all the images are loaded. We also need to set their positions to absolute.

For the pre-loader we just set some styles to make sure it get’s displayed in the correct position : in this case 70px from the top and horizontally in the middle of the container div. We also make sure to set the display attribute to “inline”, thus making sure the pre-loader img is shown while all other img’s are hidden.

Now for the Javascript/jQuery:

var speed = 50;
var pic, numImgs, arrLeft, i, totalWidth, n, myInterval;

$(window).load(function(){
pic = $(“#slider”).children(“img”);
numImgs = pic.length;
arrLeft = new Array(numImgs);

for (i=0;i

  • We use $(window).load() instead of the standard $(function(){}) or $(document).ready() methods due to a timing glitch in Safari. Safari reports the DOM as finished loading even while images are still downloading – not ideal if we want our pre-loader to work correctly.
  • When the DOM has finished loading, and the images have finished downloading we execute our code.
  • First we read all our images into an array of jQuery objects. We make sure the pre-loader isn’t included in this array by using $(“#slider”).children(“img”) instead of $(“#slider img”).
  • Next we loop through each image in our array and calculate a totalWidth. We need this value so that we know where to append each image when needed. Within this loop, we also set the correct absolute position for each image so that they all line up next to each other. Otherwise they’d all just sit on top of each other.
  • Once our loop is complete and we have all the initial positions setup, we create a standard javascript interval. Using this interval we can call a function every x milliseconds. We use the “speed” variable to make this configurable.
  • Now that everything’s set up, we hide our pre-loader, unhide our images and wait for the interval to fire.
  • The “flexiScroll()” function simply moves each image to the left by 1 pixel, recalculates the totalWidth and if necessary, moves the left-most image to the end of the list. Since the end of the list is currently outside of the viewable area, this gives the illusion that the list never ends.

    And that’s all there is to it.

    There of course must be a more efficient way of doing this, so if you would like to contribute, please leave a comment or contact me.

    Advertisements
    1. David
      May 6, 2009 at 3:37 pm

      It’s Beautiful!

      • May 6, 2009 at 3:43 pm

        Thanks David, hope you find a good use for it šŸ™‚

    2. Sergey
      May 10, 2009 at 9:05 pm

      How to do what did pictures move with left on a right? thank you!

    3. Rares
      May 13, 2009 at 1:44 pm

      Hello,

      Can you please help me modify the flexiScroll() function to achieve scrolling in the opposite direction?

    4. May 14, 2009 at 7:26 am

      Hi @Sergey, @Rares

      I’ll have a look at that for you as soon as I have a moment, it shouldn’t be too difficult (in theory).

      In the meantime I’ve found another jQuery plugin which does the same thing as my little function above. I’m just not sure if you can also move in the opposite direction. You can find the plugin here : http://logicbox.net/blog/simplyscroll-jquery-plugin/ . Give it a go and let me know if you come right with it.

      • Joseph
        August 30, 2009 at 1:02 am

        Your script is waaaay superior to the simplyscroll script referenced above. The only thing your script is missing is some extra functionality, however as a horizonal scroller it is excellent.

        • August 31, 2009 at 6:57 am

          Thanks Joseph,

          As soon as I get some more free time (probably next century) I’ll implement some of that missing functionality.

    5. Tom
      June 12, 2009 at 7:53 pm

      Nice script. exactly what I was looking for at the moment šŸ˜‰

    6. Lue
      June 30, 2009 at 5:25 am

      Awesome!! For some reason, I tried making the images a link (clickable), and everything comes up blank! Is it something in js that is not allowing that?

    7. July 10, 2009 at 6:32 am

      Thanks for your tut

    8. July 17, 2009 at 5:33 pm

      Awesome work man šŸ™‚
      I was just looking for the same thing…the only thing I would ask and suggest that cant this slide be a little more smooth?

    9. July 19, 2009 at 5:51 pm

      Hi Calisza

      Perfect. Very usefull script. Thank’s.

      // Steeven

    10. July 19, 2009 at 6:02 pm

      By the way.
      The script doesn’t work in Opera browser.

      // Steeven

      • July 19, 2009 at 8:19 pm

        Sorry, it does. I was to quick there.

        // Steeven

        • Jason
          January 13, 2010 at 8:56 pm

          Actually, there is still some kind of problem. The first load, all pictures get stuck up on each other in a strange way, while the script itself seems to be working as it should.
          The next time you reload the page, everything works fine. I guess it is something with a opera’s way of loading images and reporting if everything is loaded.

        • January 16, 2010 at 8:18 am

          Hi Jason,

          Thanks for the heads-up, haven’t tested in Opera so I’ll need to have a look at it shortly.

    11. veer
      September 29, 2009 at 1:23 pm

      please provide the code if somebody has changed the flexiScroll() function to achieve scrolling in the opposite direction?

      my id is iterveer@gmail.com

    12. Xnyl
      February 13, 2010 at 2:23 am

      Big beer for U. That was exacly what I was looking for. Thanks for accurate how-to description šŸ™‚

    13. fishtail
      February 18, 2010 at 10:02 am

      Hi.

      Thanks for the work you’ve done…

      I am wondering if it’s possible to have text appeared on the bottom of the picture, and the text scroll with the picture.

      Thanks again and keep up the good work!

    14. March 31, 2010 at 8:31 pm

      Great slider… its moving quite slow on the PC and I have tried to change the speed variable, but it seems to have no effect.

      • April 1, 2010 at 4:25 pm

        Thanks Asiano.

        Admittedly, the algorithm used is not the most efficient around, so the more images you use the slower it’ll get. The smoothness and speed of the animation also depends quite a bit on the individual PC’s memory and CPU. Javascript isn’t the most animation friendly engine, since that’s not exactly what it was originally built for.

        Hopefully advances in browser tech and support for HTML5/CSS3 will make animations like this both easier to achieve and produce a smoother end result.

        That being said, I hope to get a chance in the next few days to review the code used in this snippet and make it a bit more efficient.

    15. April 20, 2010 at 1:50 am

      This function should do the oposite dorection trick. Hope it helps.

      function flexiScrollRight(){
      for (i=numImgs-1;i>-1;i–){
      arrLeft[i] += 1;

      if (arrLeft[i] >= width){
      totalWidth = 0;
      for (n=0;n<numImgs;n++){
      totalWidth += $(pic[n]).width();
      }
      arrLeft[i] = arrLeft[i] – totalWidth;
      }
      $(pic[i]).css("left",arrLeft[i]);
      }
      }

    16. April 20, 2010 at 2:18 am

      Oh, I have forgotten something in my solution. You will need to declare the width variable (where the others are)

      var width;

      and assign the value in the window load function

      width = $(‘#slider’).width();

      I hope that now it is complete. šŸ™‚

    17. April 21, 2010 at 10:03 am

      Ok, mate, sorry for flooding your blog, I hope this is going to be the last post. šŸ™‚ The thing is that I have managed to add controls to your script and some minor enhacements. You can read about, criticise and download the final result here: http://petiar.sk/clanok/circular-image-slide-with-jquery

      Take my contribution as a “thank you” for your script. It saved me lot of time and made one of my customers very happy. šŸ˜‰

    18. Patrix
      July 20, 2010 at 8:25 pm

      Hi, great stuff.
      any way to link images with a href?
      thanks!!

    19. Kevin
      October 6, 2010 at 1:23 pm

      I’ve copied everything in an html-website and tested this out in several webbrowsers (Safari, Chrome and Firefox so far) and I’ve encountered some problems.
      Chrome: displays all images correctly, but I have the impression that when I hover over a specific part that the animation accelerates a bit.
      Safari: only shows me a part of the pictures even though I changed the height to for example 400px.
      Firefox: doesn’t show me anything. I get a blanc page and when I look at my index.html page with Firebug addon in firefox it shows me that I dont have any content in my body part.

      Really weird, anyone any ideas about this?

      Kevin

      • November 19, 2010 at 3:55 pm

        Hi Kevin,

        can you post a link to your implementation? This script works fine for me and my customer…

        Thanks,
        Petiar.

    20. dianna
      January 19, 2011 at 2:46 am

      Hello – This is a nice simple script! Can you help me figure out how to add a right margin to each of the images?

    21. Sarika
      July 21, 2011 at 10:58 am

      How can I add a hyperlink to the scrolling images?

    22. Geo
      September 20, 2011 at 4:12 pm

      Perfect!

      Searched for ages before I found this :D. Thank a million!

    23. January 16, 2012 at 9:56 pm

      how to make those images linkable? “href” makes them invisible

    24. January 16, 2012 at 11:31 pm

      Solution for those, who want to add a link into their images. In js oyu have to change path for variable pic:

      now its
      pic = $(“#slider”).children(“img”);

      make it like this:
      pic = $(“#slider img”);

    1. No trackbacks yet.

    Leave a Reply

    Fill in your details below or click an icon to log in:

    WordPress.com Logo

    You are commenting using your WordPress.com account. Log Out / Change )

    Twitter picture

    You are commenting using your Twitter account. Log Out / Change )

    Facebook photo

    You are commenting using your Facebook account. Log Out / Change )

    Google+ photo

    You are commenting using your Google+ account. Log Out / Change )

    Connecting to %s

    %d bloggers like this: