how to create a simple automatic image rotator using jQuery

Rotate II by FatalBite on deviantART

I’ll explain a simple way to create an automatic image rotator using jQuery. First have a look at the demo page (opens in a new tab) to understand what we’re trying to accomplish. You can also download the tutorial’s source code.

In the example, the initial image will be displayed on the left of a paragraph containing some sample text:

First, we have to store the filenames of our images in an array. We also have to initialise a counter.

The next step is to create the function which will rotate the images. We’ll call it rotateImage(). At the beginning, the currently displayed image fades out. Then, we load the next image from the images array (the counter we introduced before is being used here) and we fade it in. At the end of the function, we deal with the counter (either increment it, or reset it if all the imaged were displayed).

The last step is to call the rotateImage function repeatedly inside the $(document).ready function using setInterval. In the example, the function rotateImage() is being executed every 2.5 seconds (2500 milliseconds).

The complete JavaScript code:

HTML:

If you haven’t done it already, have a look at the demo page (opens in a new tab). You can also download the tutorial’s source code.

Photo by ~FatalBite

  • http://asp-net-3-5-hosting.blogspot.com/ trendbender

    I will use it in my current site, thx.

  • http://www.yuliang11net yuliang11

    great, i thought it would be easy to code. it took me hours to find the right sample rotator code. :(

  • http://www.yuliang11.net yuliang11

    thanks for it. tested, worked like a charm! now gonna implement it to my other website

  • http://www.yuliang11.com yuliang11

    just one question, anyway i can link the image rotated to a specific ahref tag ? tq

    • asd

      its not working properly when I scroll down the page. When image changes it is focusing on the image… wherever I might be on the page, it automatically redirects to me at image (when image changes).. Else working fine.. good try.

      • Stathis

        Hello, this comment will solve your issue. :)

  • sldesigns

    Thank You for posting this. It took me a long time to find a simple, yet effective image rotator that didn’t involve alot of tweaking.

    One thing I’ve noticed is that when the images are first going through the rotation, it will repeat the previous image before displaying the image.

    For example, lets say I have three images (Image1.jpg, Image2.jpg and Image3.jpg) and a transition set to 6 seconds (6000).

    Image1.jpg will display and hold for 6 seconds and fade out to display Image2.jpg. Right before Image2.jpg displays, Image1.jpg will display again quickly and then Image2.jpg will display and hold for 6 seconds. Also, right before Image3.jpg displays, Image2.jpg will display again quickly and then Image3.jpg will display and hold for 6 seconds. This only seems to happen during the first cycle but afterwards it works just fine. I have gotten this to occur in IE 8, FF 4 and Chrome. Any help you could give me would be appreciated!

  • Sonali

    Thanks a lot for this I will use this in ceptsolutions.com …. I really appreciate :-)

  • Stathis

    A question from warren (via e-mail):
    “Is there any way for the image rotater to only display the images once and then stay on the last image instead of continuous looping?”

    A solution of the top of my head would be to add a boolean variable at the beginning of the script and then modify the rotateImage() function to change this variable to false when the array of images reaches the end, adding an if statement to make sure it will only perform the rotation when the variable is true:

    var rotate = true;

    function rotateImage() {
    if(rotate) {
    ...
    if (index == images.length-1) {
    rotate = false;
    }
    ...
    }
    }

  • John

    Thnx!

  • Saravanan C

    Hi burnmind,

    It is very useful for me!

    Thanks to burnmind.

    Regards,
    saravanan.chandrasek

  • Graham

    I have implemented this on my site which is great. My only concern is that when i scroll down the page, when it loads the next image, the page jumps to where the images are. Do you know why or for a solution?

    Thanks!

    GREAT WORK BTW!!!

  • Stathis

    Hello Graham,

    You can do the following:

    Place the image into a div and give it a class called “image-holder”. Then, style the class like that (you can also remove the float & margin from the styling of the img tag):

    .image-holder
    {
    width: 150px;
    height: 150px;
    float: left;
    margin-right: 10px;
    }

    That will fix your issue.

  • Chris

    Hello Burnmind,

    I was just wondering, and it seems that a few others have had the same question I have, how do you create a link for each rotating image? What is the best way to go about this? Other than this little question the code is working great! Thanks!

  • Stathis

    Hello Chris,

    First, wrap the image with an anchor tag and set at the href attribute the URL that you want to relate with the 1st image (e.g. http://url1).

    Then, add the following outside of the rotateImage() function (before it):

    var urls = new Array (‘http://url1’, ‘http://url2’, ‘http://url3’);

    Finally, add the following inside the rotateImage() function (where the src substitution occurs as well):

    $(‘#myLink’).attr(‘href’, urls[index]);

    And you’re good to go!

  • http://www.golfresortsandmeetingdestinations.com Chris

    Thanks a lot!

    It works like a charm! There are a few kinks that I still need to workout that I can’t figure out. But other than that it is functioning properly. I am having some serious issues with Internet Explorer, when the page is loading the first image will repeat itself four or five times then it will eventually get back on synch with how it is supposed to be. I have no idea what it could be. Any suggestions would be helpful. Thanks for your help on the linked images though, that worked extremely well!

  • burnmind

    @Chris: With which version of IE do you have issues? Please post any changes you’ve made to the code (or provide a url if you have uploaded it somewhere) so I can try to replicate the problem on my end to help you solve it.

  • Chris

    Here is the link to the website:

    http://www.golfresortsandmeetingdestinations.com

    The only alterations I really made were to preload my images, but other than that I can post all of my code if it helps. I believe I tested it on IE 9. It also loads the first image twice in Firefox and Chrome as well (Let me know if it does the same for you). I am not sure if it is because I preloaded the images or what. Thanks so much for all your help. I greatly appreciate it.

  • Stathis

    First of all, move the href substitution [ $(‘#myLink’).attr(‘href’, urls[index]); ] inside the fadeout function, where the src substitution [ $(this).attr(‘src’, images[index]); ] is located as well. It won’t fix the problem, but this is how I tested it a few comments back. :)

    In Chrome it doesn’t, but in IE9, Firefox & Opera it loads the first image twice and then continues normally. That happens only in the first visit. In every other one it works as it should. It happens again only if I clear the cache and then revisit.

    Therefore, the problem should be the pre-loading function that you use. Try to remove it to check how it works (remember to clear your cache first) and then, if you decide that you need it, insert it inside the document.ready and manipulate it so the [ setInterval (rotateImage, 3800); ] starts after the pre-loading has finished.

  • http://www.bigboom.co.za dave

    thanks for the code, its so small and efficient.

    Is there any way to fadeOut and fadeIn at the same time so that there is no empty space between images?

  • Stathis

    @dave: I don’t believe that it’s possible using fadeOut and fadeIn. Maybe you can try and work something by using fadeTo() to fade the image to a specific opacity, then change the src of the image, fade it back to 100% etc.

  • Hitesh

    The first initial image which is given in src with div tag , that is being displayed but after that the “Image Test” is getting displayed…..

  • Stathis

    @Hitesh: Please rephrase your question because I cannot understand the problem you’re describing.

  • LBlake

    Finally – something straightforward and simple – excellent! Works great. Thank you!

  • ethan

    Hey,
    when you set a value for “set interval” it will take effect before the first picture even shows up.
    is there any way to make the “set interval” value kick in after the first image was shown?

    Thanks!

  • Stathis

    @LBlake: thanks :)

    @ethan: The first image is “hard-coded” into the img tag. The setInterval starts counting as soon as the page has finished loading (since it’s located inside the document.ready function), therefore what you’re describing is already happening. If you mean anything else, please explain in more detail (an actual example of the problem will be useful as well).

  • http://www.ughdating.co.uk cooljules

    I’m having a similar problem to burnmind. You can see on the homepage http://www.ughdating.co.uk that the animation should go from each description to each associated photo. But it gets itself out of sync randomly and repeats bits. E.g. I watched it 3 times in a row, first two times it works correctly, third time it repeated one of the text descriptions and got out of sync. Seems to happen in IE or Firefox.

    TBH, its like the set interval is buggy. But wanted to mention it.

  • Stathis

    @cooljules: I believe that your problem lies on the fact that the images are being loaded the moment JavaScript changes the src of the img tag. There, a GET request is being made and your server returns the image; you can monitor this process (and the time needed for the server to return the image) using tools like Firebug or Webkit Inspector.

    I’ve tested your site in every major browser and sometimes during the first visit, some of the large images (the photos which are 200-300+ kb) fail to load quickly, so the problem you’re describing appears. In every next load, the images are being loaded from the browser’s cache, so the problem vanishes.

    One solution is to pre-load the images. Another solution is to lower the size of the large images.

    Nice design btw!

  • http://www.ughdating.co.uk cooljules

    I did think about preloading the images, however for me, it randomly gets out of sync on the 3rd or 4th rotation (i previsouly had it on continual rotations) by then, my computer had already cached the images.

    Good point on the size of images though, I must have got photoshop in the wrong compression rate for them to be that big!

    Thanks for the design comment :)

  • MikeB

    I followed your suggestion on 2/13 and 2/21 for adding url variables. The url never seems to update. I thought perhaps adding id=myLink in the anchor tag was what was missing but no luck.

  • MikeB

    Got it solved. For some reason there was an issue with the single quotes. I copied and pasted from the post on 2/13 and Aptana kept telling me I had an illegal character. I tried escaping the forward slashes to no avail. I retyped the whole line of code and now it works just fine. Thanks for this great little script.

  • Stathis

    @MikeB: Yes, copying code sometimes can produce a strange outcome especially with characters like quotes. I’m glad you solved it and thanks for the kind words. :)

  • http://www.mushroomharvest.com Judith

    burnmind,

    Wonderful little script/tutorial! Thank you!

    I do see one issue that “sldesigns” mentioned 5 May 2011. I am seeing the same behavior where the images will fade out (as expected), then flash (for about 1 sec) before loading the next picture in the array. This is happening with FF 13.0 (beta).

    Depending on when you read this, you can see the behavior at http://mushroomharvest.com/Templates/Mushroom_default_colors/ or simply at http://mushroomharvest.com/

    Any suggestions on eliminating the ‘flashed” image?

    Thanks!
    Judith

  • Stathis

    @Judith: As it was discussed in other comments as well, try preloading the images which should eliminate such problems.

  • http://www.healthaccesstz.org fad

    thank you burnmind, for the nice short tutorial, you really cant measure how much you have helped me.I have tried it on my pc it works great.
    However am facing a little problem, i hosted my web inside wordpress on the server, now i dont know exactly how to call those images and the js files or should i just place them as they are?

  • Stathis

    @fad: Thanks. :)

    You’ll have to load the .js files from inside the head tag of the theme you’re using (you’ll find it in your theme’s header.php file). Also, find the path of the images (where you uploaded them) and include it in the js code along with their names.

  • http://www.healthaccesstz.org fad

    ok cul thanks for the reply!!

  • Suz

    I can’t get this work. The image just flickers but doesn’t change to the other images.

    Any suggestions please?

  • Stathis

    @Suz: Please read all the comments and if you still have a problem please upload your code somewhere and provide the url to check what’s going on.

  • David

    This my friend is so far, the simplest rotator I’ve seen.
    Thank you for the simplicity lesson, awesome, simple, clean and easy.
    Love it!

    • Stathis

      Thanks :)

  • http://8am.pg Tonichi

    Hi I was trying put a link but it wont work on mine:

    is this correct?
    $(‘#imageSlide2’).fadeOut(“slow”, function() {
    $(this).attr(‘src’, imgs[(imgs.length++) % cnt]).fadeIn(“slow”);
    $(this).attr(‘href’, urls[(urls.length++) % cnturls]);});
    }

    • Stathis

      Please read this comment, where I explain one of the ways that you can add a link.

  • Chirp08

    A simple modification can be made to make this look much smoother. If you wrap your image in a div of the same size then set the background of that div to the next image in your array you can achieve a nice crossfade between the two images instead of going to white in between.

    Add this line above the myImage fadeout line:

    $(‘#homeRotator’).css(“background-image”, “url(” + images[index] + “)”);

    It works best if you set your fade out to a larger time like 2 seconds, then set your fade in speed to something small like 250. I’ve found that making the image instantly visible (instead of fading it in) causes a flicker/glitch, so even though its unnecessary it looks best to keep the fade in still. Remember to change #homeRotator to the div name. Also set the css properties of the wrapper div to the size of your image, and background-repeat to none to be sure nothing else appears at the edges of your images.

    • Stathis

      I haven’t tried it yet, but it sounds like a good idea. :)

  • http://www.webitechi.com Sreelal G Pillai

    how can we make a horizontal image only rotator??

    • Stathis

      Can you provide an example of what you’re looking for?

  • Anthony

    Thank you, that was easy.

    • Stathis

      You’re welcome :)

  • Ramu

    Good one.

  • paul.mac

    Here is my script:

    var panoramas = new Array(“headerimage11”, “headerimage”, “headerimage2”, “headerimage3”, “headerimage4”, “headerimage5”, “headerimage6”, “headerimage7”, “headerimage8”, “headerimage9”, “headerimage10”, “headerimage12”, “headerimage13”, “headerimage14”, “headerimage15”, “headerimage16”, “headerimage17”, “headerimage18”, “headerimage19”);

    var i = 2;
    var myTimer;
    var refreshTime = 3500;

    function rotateImage(){
    $(‘#panoramaImage’).fadeOut(1000, function(){
    $(this).attr(‘src’, ‘images/’ + panoramas[i] + ‘.jpg’);
    $(this).fadeIn(1000, function(){
    if (i == panoramas.length – 1){
    i = 0;
    }else{
    i++;
    }
    if (i == 0){
    clearInterval(myTimer);
    refreshTime = refreshTime * 1.25;
    myTimer = setInterval(rotateImage, refreshTime);
    }
    });
    });
    }

    $(window).load(function(){
    myTimer = setInterval(rotateImage, refreshTime);
    });

    and my HTML:

    and further down the page:

    But when it runs the first image in the loop is undefined and I get a blank. What am I doing wrong?
    Thanks

    • http://burnmind.com/ StathisG

      Can you provide a live demo (e.g. a fiddle) recreating the issue?