Easy Jquery Image Rotator
The other week I had a friend ask me for a simple script to rotate a few images on his web page. Sounded simple and I even assumed I would not have to re-invent the wheel, but after an hour of searching for a lightweight script I was surprised to find that unless you were willing to install rather large plug-ins along with jquery there were not allot of options for the simple rotation of images except out-dated scripts. So I decided to come up with my own image rotator that uses jquery's already built in effects.
Jquery Image Rotator Functionality Checklist.
What we need our Jquery image rotator to do:
- Rotate Images with Links.
- Valid XHTML.
- Lightweight Script.
Let's look at the XHTML, CSS, and Jquery Javascript that makes it work.
Jquery Image Rotator, View Demo, Download Source.

The HTML for our jquery image rotator gets placed in the body of your page.
<div id="rotator">
<ul>
<li class="show">
<a href="javascript:void(0)">
<img src="images/image-1.jpg" width="500" height="313" alt="pic1" />
</a>
</li>
<li>
<a href="javascript:void(0)">
<img src="images/image-2.jpg" width="500" height="313" alt="pic2" />
</a>
</li>
<li>
<a href="javascript:void(0)">
<img src="images/image-3.jpg" width="500" height="313" alt="pic3" />
</a>
</li>
<li>
<a href="javascript:void(0)">
<img src="images/image-4.jpg" width="500" height="313" alt="pic4" />
</a>
</li>
</ul>
</div>
The CSS
/* rotator in-page placement */
div#rotator {
position:relative;
height:345px;
margin-left: 15px;
}
/* rotator css */
div#rotator ul li {
float:left;
position:absolute;
list-style: none;
}
/* rotator image style */
div#rotator ul li img {
border:1px solid #ccc;
padding: 4px;
background: #FFF;
}
div#rotator ul li.show {
z-index:500;
}
The JavaScript
Include jquery and the below script in your page or in an attached file.
To activate jquery image rotator place the above code in your page head or an attached file. You can adjust the time before the next image appears by altering the setInterval value as well as the fade time itself by changing the animate duration.
Filed in Design Tips & Techniques and tagged design, html, javascript, jquery, web
















Great stuff thanks, any way to do pull the images gallery from a folder with php?
Yes I will post an update shortly.
I shortened the html output because I saw no use for the additional block level div in addition to the ul but here's how to get the files out of a directory with php, at least this is how I did it:
http://snipt.net/dmoore/grab-image-files-from-directory/
You would have to amend the code for the jquery script as well. Just go through and change all instances of 'div#rotator ul li' to '#rotator li'.
Thanks Derek, that is very helpful. :)
You're welcome. :)
Thanks for sharing such a straight forward solution Derek. I went ahead and mocked up a demo including your php code.
Jquery Image Rotation with PHP
Just be sure to assign the width and height of your images within '#rotator li img' or the php itself so that internet explorer can render it properly.
Thanks for the great tutorial.
One thing tho... when I remove the absolute tag to position it differently the images start scrolling down the page. Is there away I can change the position of it without it doing this?
Many Thanks
Hi santiago, yes you could try position relative and add or adjust margin and or padding for placement.
This is one of the best image rotators I've seen. The only thing I'd love to see included is a delay for the fade. I put three rotators on a client site and I want the rotate interval the same but I don't want all three to rotate at the same time.
Great Work!
Thanks Christopher,
To adjust the delay for the fade time between pictures you can set the interval towards the top of the script. The default is 6 sec if you would like a 3 second delay for example you would change the 6000 to look like,
setInterval('rotate()',3000);
3000 = change to next image after 3 seconds. Hope that helps. Thanks Again
Hey this is pretty sweet and much easier than other solutions I have tried. Nice work. Couple questions/requests, Is there a way to add a clickable tag to the images ? I have tried but have not succeded. Also can I place this in several defined locations on to of one background image on my page ? background image is 900 x 380 and the images I am using for the rotation are roughly 30x30px. Any help would be great
Hi Flexxall,
The images are click able you just need to insert the href address that you would like it to point to within the html.
To add a background image you would place a container div tag around the image rotator and assign it a background image via css.
Ok great I have all that working wxcept for one part. I am un able to get multiple fade locations on top of the same background image. I have one image that I would like 10 different instances of the fader to be located on. Id also like to add an array to pull the images from but im not having much luck with that. Thanx for the help thus far :)
Wow this generated a lot of buzz Dylan. It looks like you've advanced it too. The client this was generated for decided not to use it after a month or so.
What I don't see here is where the a href can change along with the image. Am I missing something?
Hi Jesse,
Conceptually this image rotation works by switching the z-index and opacity of each list item which contains an image. Kind of like a stack of cards that you flip though. So each list item has its own image and a href which is currently set to javascript:void(0).
If you take a look at the demo again you can see as each image comes up the link changes from #link1 to #link2 and so on when the image is clicked.
I went with this method because it is very seo friendly due to the fact that the links are not dynamically generated and are thus always visible to search engines.
Quick question -- I'm trying to implement this on a development site and the links aren't updating as the image rotates. The images are working fine, but they all have the last a href=" " associated with them instead of their unique link that I've added in the code. Not sure what it could be. Any ideas?
Sorry, that code garbled a bit -- should say "...all have the last link associated with them...." (ie. the link on the last list item is applied to all list items).
Aloha Laryn,
I have adjusted the demo to use actual website urls and cannot replicate your issue as all the links seem to work fine on my end. Perhaps it is a simple issue of a misplaced or missing " in your a href code. A working example might help to figure out what is going on.
Ah ha!
The text on the page is missing a semi-colon after "z-index:500" and I didn't notice that. (I cut and pasted from the page, not the code on the demo page). Works now -- thanks!
Some great stuff, is there a way to make images load randomly and not in order?
Aloha Danny,
yes there would be several ways of going about having a random image displayed but I would think that tweaking the php which pulls the images from the folder would be the easiest way. There are several php scripts that do this found on google using a search phrase like random images from folder with php. Here is an example.
Hope that helps. :)
Great thanks Dylan for the script. The rotator works fine except when it's got only one image to work with; then it fades and flashes to white. Any suggestions?
Not sure if I'm double-posting now, but how does the Rotator deal with having one single image to rotate? (I gather images by means of mySQL). The Rotator misbehaves badly and flashes and fades to white. Any suggestions, anyone?
As we say on the western reaches of the western island off western Europe "this is the dog's bollox" - which is an emphatic (but slightly rude) compliment. jQuery is super but it is really nice (and not that usual for newbies) to have some help using it without plugins.
Thank you many times!
Your very welcome. :)
Yeah, we modified the script (with Dylan's help) or maybe he did it all. I forget.
To use divs instead of images. It wasn't hard.
Then you could load a portion of html into any of the divs. Such as an image, image and text, flash, whatever.
For you you could use two divs with the same html perhaps to fade into itself?
Not sure I understand why you would rotate something with itself though.
Say if you have it pulling a random number of images from a random directory..
You may end up with only one, then it will flicker?
What if you have 100 images.. is there a way to not require the images to be in the html? Maybe only have two li tags to rotate but swap out the img source of the one not being displayed?
I like the fact that your rotator requires no plugin!
Also,I'm no javascript expert, but I have written a function in php to convert a php array to javascript array that I can share if you'd like..
Hi Dylan
Super script thanks. How do i slow down th efade effect from one image to next? I dont mean the interval between images, just the fade. It seems a bit fast for my requirements.
Thanks again!
John
Hi,
Apologies if this has come up before.
Great demo.
One Q.. in Firefox's error console it always states unknown pseudo-element / class 'first'.. is there any way to get around this? This also leaves the 'errors on page' in IE.
Thanks.
How would i stop the rotation when someone clicks? Something like...
$(document).bind('mousedown',function-to-stop-rotation?);
To avoid the "blank image" if you have only one item replace
setInterval('rotate()',6000);withif ($('div#rotator ul li')).length > 1) {setInterval('rotate()', 6000);
}
Thank you for posting that solution. Also on a side note I had a database failure from an unknown MT bug or other. Thanks to a complete tables backup login, registration and comments have been restored.
Hi, this is a great plugin, Simple to set up and get going I had it done in minutes.
However I'd like to be able to do some more with it:
1- Start at a random image from a folder but continue in the folder order from there.
2- change the rotation time for each image. I have one animated gif that is approx 24 seconds long and will be shown every 4th image but the other images should be shown for 10s each
So the rotation will be something like this:
1- 24s image
2- 1st img from folder selected randomly
3- following img in folder order
4- following img in folder order
5- 24s image
is there a way to do this?
To get the banner to fade-in at the first image (instead of it plopping into view and only fading following images) put these 2 lines at the bottom of the javascript, right after theRotator();
$('#rotator').fadeIn(1000);
$('#rotator ul li').fadeIn(1000); // tweek for IE
Then in the CSS add "display:none;" to the list of div#rotator attributes.
Lastly, continue with a bit of tweeking for IE and put these styles in an IE only stylesheet AFTER the main CSS for this rotator;
div#rotator { display:inline; background:url("images/image-1.jpg") 0 0 no-repeat; }
div#rotator ul li { display:none; }
(Notice how you set the background image of div#rotator as the first image from the rotator list.)
For IE only stylesheet help, see here: http://css-tricks.com/how-to-create-an-ie-only-stylesheet/
ps - This fade-in revision will also fix the problem where you see all the images load in for a split second on every page refresh.
Tested in IE6,7,8,9, FireFox 3, Safari 3 Windows, Opera 9/10, Chrome.
Great stuff, but got a problem using png's with transparency. Compare this page with Firefox 3.6 and IE:
http://heatondev.com/fasttrack/template/homepage.php
I'm sure theres an IE hack to fix this but my web-fu isnt up to it. Anyone got an idea?
All the images look fine in IE when loaded separately- see here: http://heatondev.com/fasttrack/Images/rotator3.png
When 'rotated', they look a bit, well 8-bit.
replying to my own question... should have known really that changing the opacity of png's doesnt really work in IE. Use gifs is about the only option.
Hi,
I have installed image rotator, but cannot get the banner in the right place. The site is 82industries.com/index.htm but I'd like the banner in place like 82industries.com/index.html , what can you or anybody charge me to do that?
Stevo - sorry for just jumping in here, but do you mean like this : http://heatondev.com/temp/
I took the liberty of copying your site and hosting it temporarily on my host so i can show you the changes. I didnt get all the images but the positioning looks a bit better. Your image is very wide though, and your table layout could be vastly improved by using pure css. Anyway, have this one on me, just save the page back to your host.
Neat stuff and thanks to everyone for helping me get it functioning!
Image Rotator is hard at work! Is their HTML to add to resize the banners, they run wide (on smaller screens) and viewer would have to scroll to completely view. The site is 82industries.com and look forward to reply...thanks
I never usually write on posts, but I had to for this. Being a complete novice, I wanted a simple Image rotator on my site without having to know too much about Javascript etc. This was the perfect solution, so easy to implement and is fantastic to view. Thank you for a great product. Gino
Your very welcome, glad it helped.
nice web
Great Image Rotator!!
It works great, but I have just one thing I cannot seem to figure out.
Are there any special tweaks to get the images to rotate (even if they don't fade) in IE7?
It's working great in Firefox, but in IE7, it just seems to show the last image in the list, and sometimes show the second to last image...
Any help would be greatly appreciated!
Hi! I love this image rotator! It works great! I wanted to make one modification for my own usage though. I have tried to play around with the code, but I have so far been unsuccessful at making this image rotation happen on mouseover instead of automatically. How would I go about this?
I'd really appreciate any help I can get :)
Thanks!
Ena
I know you're asking about using jQuery, but you can achieve a mouseover effect using simple CSS.
For example:
#element {
width: 100px; /* width of image */
height: 200px; /* width of image */
background-image: url(/path/to/image.jpg);
}
#element:hover {
background-image: url(/path/to/other_image.jpg);
}
To do this in Jquery the script would be entirely different than the image rotator above.
Right now we are using setInterval and setTimeout which can sometimes be a bit tricky because they always reference the window object.
However if we use a simple nested function inside the change() function and then reference that with setInterval, it ends up working just fine.
So your code above would look like this:
function change(id){ clearInterval(changetimer); function swap () { if (id.src.match("/1.jpg")) { id.src = id.src.replace("/1.jpg","/2.jpg"); return false; } if (id.src.match("/2.jpg")) { id.src = id.src.replace("/2.jpg","/3.jpg"); return false; } if (id.src.match("/3.jpg")) { id.src = id.src.replace("/3.jpg","/1.jpg"); return false; } } changetimer = setInterval(swap,1000); }That would leave you with clean htnml markup like this: So putting that javascript together would look like this:var changetimer;
function change(id){
clearInterval(changetimer);
function swap () {
if (id.src.match("/1.jpg")) { id.src = id.src.replace("/1.jpg","/2.jpg"); return false; }
if (id.src.match("/2.jpg")) { id.src = id.src.replace("/2.jpg","/3.jpg"); return false; }
if (id.src.match("/3.jpg")) { id.src = id.src.replace("/3.jpg","/1.jpg"); return false; }
}
changetimer = setInterval(swap,1000);
}
window.onload = function() {
var images = document.getElementsByTagName('img');
for (var i = 0; i images[i].onmouseover = function(evt) {change(this);};
images[i].onmouseout = function(evt) {clearInterval(changetimer);};
}
}
I know it seems a bit much but all we are doing is switching if image1 with image 2, if image 2 with image 3 and so on. Hope that helps.
Hello! Thank you so much for this, I'm a noob when it comes to js, and I would like to know how to use this exact effect but for background of my html. I'm sorry if this is an stupid question.
Thank you!
Hi! I love what you've done here!
I have very limited javascript knowledge so bare with me. I can get the rotator to work only when the javascript is pasted into the XHTML, but I'd really like to have it be in it's own file.
When I pasted your Javascript code into it's own file in Dreamweaver, it told me that there is was syntax error in line 5. (?)
Do you have any idea why this wouldn't work? It shows all the images at once instead of rotating them. I have an example below.
http://www.insightcreative.com/temp-ang/index-copy.html
Thanks in advance for your help! I love your site!
Hello,
To: rq! Yes you would make the rotator div your main background container div, size images appropriately and layer everything else above it using z-index.
To: akmurphy. Try the View Demo or Download Source towards the top of this post to copy and paste usable code. If you take it straight from the text box on this page the browser tweaks it a bit on copy/paste due to pre and code tags used to display it with out executing it.
Fantastic script, so much simpler to implement than any of the others I had tried. One question though - what would I have to do to implement multiple instances of this on a single page ?
Thanks again.
M
Fantastic script, so much simpler to implement than any of the others I had tried. One question though - what would I have to do to implement multiple instances of this on a single page ?
Thanks again.
M
Really nice rotator. Even I could get it to work.
I can't work out how to break the loop though, so that it stops on the last pic.
Something to do with this:
//Get next image, when it reaches the end, rotate it back to the first image
var next = ((current.next().length) ? ((current.next().hasClass('show')) ? $('div#rotator ul li:first') :current.next()) : $('div#rotator ul li:first'));
Hello,
To: mriley. To have more than one instance we need to change the #id to a class. You can do a find and replace changing all of the div#rotator to div.rotator. You would also change the html to div class="rotator". From there you can place as many mas you like.
To: Michael, in order to have the rotator stop on the last image we need to use clearInterval()
first change the line
setInterval('rotate()',6000);
to
var rotate;
rotate = setInterval('rotate()',6000);
now change
var next = ((current.next().length) ? ((current.next().hasClass('show')) ? $('div#rotator ul li:first') :current.next()) : $('div#rotator ul li:first'));
to
var next = ((current.next().length) ? ((current.next().hasClass('show')) ? $('div.rotator ul li:first') :current.next()) : clearInterval(rotate));
Hope that helps.
Ahh of course! Thanks for your reply. Once again fantastic little script.
Mike
Ahh of course! Thanks for your reply. Once again fantastic little script.
Mike
Hi Fab stuff! thanks for this.
I am struck. Will be a great help if you can get me going. I have two JPEG's stored in the folder. The CSS looks like:
*************************
#homeContentIMGa{
width:969px;
height:554px;
position:absolute;
left:0px;
top:0px;
z-index:10;
}
#homeContentIMGb{
width:969px;
height:554px;
position:absolute;
left:0px;
top:0px;
z-index:10;
}
.homeContentIMGa-en{
background: url(../../data/img/home-en/homeContent-1.jpg) no-repeat;
}
.homeContentIMGb-en{
background: url(../../data/img/home-en/homeContent-0.jpg) no-repeat;
}
#homeContent{
width:969px;
margin:0px 0px -20px 0px;
position:relative;
}
#homeContent #in_homeContent{
background:#EE1C25;
}
#homeContent #homeContentTop{
width:969px;
height:296px;
/*background: url(../img/homeContentTop-bg.jpg) no-repeat;*/
}
*************************
The JS is
*****************************
$(document).ready(function(){
var chooseLanguage = "en";
$("a[rel^='photo']").prettyPhoto({
animationSpeed: 'fast', /* fast/slow/normal */
opacity: 0.80, /* Value between 0 and 1 */
showTitle: true, /* true/false */
allowresize: true, /* true/false */
default_width: 400,
default_height: 200,
theme: 'light_rounded'
});
/**************************
HOME - NEWS Slider
*/
$("#newsContent").easySlider({
auto: true,
continuous: true,
numeric: true,
speed: 1000,
pause: 5000
});
$('.do-noveho-okna').click(function(){
window.open($(this).attr("href"));
return false;
});
if ($('#homeContent').length == 1) {
/**************************
Homepage - Image loading
*/
var i = 0;
imageObj = new Image();
images = new Array();
for(i=0; i
images[i]="/data/img/home-en" + "/homeContent-" + [i] + ".jpg"
}
for(i=0; i imageObj.src=images[i];
}
/**************************
HOME - PICTURES Merging
*/
var homeContentCount = 3;
var homeContentCurrent = 1;
function homeContentIMG() {
homeContentPrev = homeContentCurrent % homeContentCount; /* 0 */
homeContentNext = ++homeContentCurrent % homeContentCount; /* 1 */
$('#homeContentIMGa').css('background', 'url(/data/img/home-en' + '/homeContent-' + homeContentPrev + '.jpg) no-repeat');
$('#homeContentIMGb').animate({
opacity: 0.0
}, 2000, function() {
$(this).css('background', 'url(/data/img/home-en' + '/homeContent-' + homeContentNext + '.jpg) no-repeat');
});
$('#homeContentIMGb').animate({
opacity: 1.0
}, 1000);
}
setInterval(homeContentIMG,5000);
}
****************************
And the Html I am calling
*************************
Now the problem I am facing is that, first image loads, but then I get a blank white background and nothing happens further...
Similar query has been asked before, but reply to that didnt help me much. I am a novoice in javascript and Jquery.
Your help will be much appreciated.
Dylan, you are brilliant. Thanks. Your suggestion worked!