Easy Jquery Auto Image Rotator

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:

  1. Rotate Images with Links.
  2. Valid XHTML.
  3. Lightweight Script.
The Rotator as I have come to call it will simply auto rotate through a list of images with a smooth fade effect without the need to include an extra plug-in on top of Jquery.

Let's look at the XHTML, CSS, and Jquery Javascript that makes it work.

Jquery Image Rotator, View Demo, Download Source.

Image Rotator

The HTML for our jquery image rotator gets placed in the body of your page.


<div class="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;
        display:none;
}
/* rotator css */
	div.rotator ul {
	margin:0;
	padding:0;
}
	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.

Related Topics

154 Comments Subscribe to this Entries Comment Feed

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 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

Dylan Wagstaff MT

Hi santiago, yes you could try position relative and add or adjust margin and or padding for placement.

Facebook

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

Dylan Wagstaff MT

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 :)

Jesse MT

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?

Dylan Wagstaff MT

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).

Dylan Wagstaff MT

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!

Dylan Wagstaff MT

Your very welcome. :)

Jesse MT

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..

Kerry Web Design MT

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

David Oldfield MT

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);
with
if ($('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!

Stevo MT

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

Dylan Wagstaff MT

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:
 <img src="images/1.jpg" />
 <img src="images/2.jpg" />
 <img src="images/3.jpg" />
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!

Dylan Wagstaff MT

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

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'));

Dylan Wagstaff MT

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

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!

Thanks, great script!
it works great! now i'm making several changes to fit my needs based on your original code, for DB management of the rotator off of a cp, and more.
If all goes well, maybe I'll be able to ad randomizing to it as well as to make other variables externally configurable.
Your script got my creative juices going =P

Hi, quick question from a complete novice - is it possible to change the image rotation from continuous to only happening when a button on the same page is clicked? For example if I had three images with three titles listed at the side of the image box and when each image title is clicked the image changes accordingly?

Hi, it works great!
I only have two questions. I need your help. thank you for it.

I using two different slideshows at the same page. When it opens, the first one runs perfectly but the problem came with second which start loading pics after the other slideshow one already load the first one. Also it only loads once and doesn't restart from the beginning just as the first slideshow does. How can I correct this problem?

In the other hand, how can I give different fadeout time to each slideshow?
For example, the fist slideshow fade every 6 seconds and the second slideshow loads every 3 seconds.

Thank you for your patience and time.

jay MT

Thanks so much for this, very simple and straight forward. My question with this and most jquery rotators I have found has to do with alignment. Lets say I have a div that is 400px x 400px and I want to rotate different sized images that are centered horizontally in that div? Any ideas how I can achieve this?

Hello Jay you can accomplish centering various images within a div tag via css.

For example:

div#rotator ul li img{
display:block; /*allows the element to take auto margins*/
margin:0 auto; /*centers in compliant browsers*/
text-align:center; /*centers in old versions of IE*/
}

To cosme212:

The simplest way would be to incorporate 2 separate instances of the script in the same page giving the second its own unique div names within the css html and script.

Hi, nice script works perfectly except one detail.

No matter what I try I always have 40px of padding on the left? Same result with IE or FF.

You'll notice it better if you wrap in a centered div :

#DivTest {
width: 600px;
background-color: #06C;
margin-left: auto;
margin-right: auto;
}

Great script, Thanks! I'm new to Javascript and have a question: I have four images in the rotation each meant to link to a different page. No matter what I put in as my link for the image, it seems to choose one and all images link to that same page. Any ideas on what I need to do to correct this?

Ignore my question. I figured it out from reading some of the posts above.

Love the script, but I'm having true issues with the CSS. Specifically, the images are not taking each other's place and a bullet is displaying.

Here is the test site: http://www.westernmass-squash.com/collegesquash/

Any help would be appreciated. Thanks.

outshined,

Having the same 40px left padding problem. Did you resolve?

Hi,

i would like to stop the rotator on mouseover and start on mouseout.
and ideas??

Dylan Wagstaff MT

Hello all

@Ast and outshined to remove 40 px from left side within the css remove margin-left: 15px; from div#rotator and add below.

div#rotator ul {
margin: 0px;
padding: 0px;
}

@MTB The images on test site appear to be showing fine on my computer. Did you resolve?

Hey Dylan - thanks for this great script. What I really like about it is that it doesn't blow up the page if a user has JavaScript turned off.

The only thing I'm wrestling with is the ability to have the images fade in randomly. i would like to use this for image banners across a site but I don't want to have the images appear in the same sequence each time.

Is there a way to randomize the sequence? I've tried the above example: " but the images never change - they just fade down a bit.

Am I missing something? Thanks again!

Nice script.. thanks.. I was wondering if its possible to externalise the JavaScript and the css.. place the script externally and link to the html file, but i am not able to get it to work.. any help is appreciated. says sytax error in js file at - $('div#rotator ul li').css({opacity: 0.0});

Dylan Wagstaff MT

Hi Capp, to have the images load randomly add the following right under the //Get next image function. I'll go ahead and update the script in a bit to include it commented out. That way if others would like to use it they can simply un-comment the function

//Get Images in random order
var sibs = current.siblings();
var rndNum = Math.floor(Math.random() * sibs.length );
var next = $( sibs[ rndNum ] );

Lazy: Not sure externalizes fine on my end by referencing the external .js file, just need to add the below to head or at bottom of html doc.

$(document).ready(function() {
//Load the slideshow
theRotator();
});

The css could be included in your sites current style sheet as well. Hope that helps.

Hey Dylan - thanks for the prompt reply! I added the code and it works great. It's almost perfect.

Is there a way to load a different first image each time a page loads? The images change randomly but always start with the same one when you navigate through the site. Is there a way around that?

Thanks again - I appreciate your help with this.

Thanks for replying Dylan. I am a layman at this.. I am still having problems. I externised the JS. and i added the code in your reply to my html file at bottom of doc (before). but now i dont get any errors. Firefox error console says " Warning: Unknown pseudo-class or pseudo-element 'first'.
Source File: image-rotator/image-rotator.html "
Is there anyway.. you can put link to a zip file of the same script with js externalised?..
sorry for the trouble.
thanks

Hey Dylan.. no worries.. figured it out.. works like a beaut
thank you soo much for putting this script up..

Dylan Wagstaff MT

HI Capp the easiest and best way for performance reasons would be to hard code / change the first image on each page within the ul. (Not manipulating the DOM to much is a big topic in Javascript optimization as it is taxing on servers)

Glad you got that figured out lazy.

In Firefox Addblock Plus 1.3.1 is blocking the rotator. Is there a workaround except turning off Addblock?

HI,
I am looking for a solution how to get rid of that effect when the slider gets to the last image and then slide to the first one showing each image for very short time.
I would like to have a continous loop, when after last image there is shown first one, but in smooth way, just like other images are changed.

Anybody ??

If I wanted to edit this to add a small window to the right of the images what would be the best way to do that. Kind of like how it is on www.mtv.com. If anyone has any ideas please let me know.

Wayne MT

It's a nice rotator but I prefer the s3Slider (Google it) because, among other things, it pauses when the mouse is hovered over it.

Hi, first of all thanks for this nice script.
I tried to change it for my needs but unfortunately I failed. I need various rotators on one page. What is the best way to do that? I made changes as follows:

html:
I added two divs with class="rotator" after each other and added to each div an id (gal2 and gal6) for positioning

css: your code and

div#gal2{
position:absolute;
top:0;
left:77px;}

div#gal6{
position:absolute;
top:77px;
left:0px;
}

javascript stayed the same.
The problem is that at the beginning i see only the first gallery, after the first picture fades to the second, the second gallery becomes visible, after rotating of two pictures in both galleries dissapeares the second gallery and only the first one stays visible.

Here can you see what I mean:
http://members.chello.at/100glava/luxury/index2.html

I also tried to give each rotator an id and to pass it as parameter to theRotator function, but it also didn't worked.

I'll appreciate for your advice :-)

Hi, first of all thanks for this nice script.
I tried to change it for my needs, but unfortunatelly I failed. I need various rotators on one page. What is the best way to do that?
I made changes as follows.
html: two divs with class rotator after each other, each become an id for positioning
css: yours plus div#gal2{
position:absolute;
top:0;
left:77px;}

div#gal6{
position:absolute;
top:77px;
left:0px;
}
javascript stayed the same.
The problem is that at the beginning I see only the fist gallery, from the second picture I see both galleries, and after rotating of two pictures dissapeares the second gallery.
Here can you see what I mean:
http://members.chello.at/100glava/luxury/index2.html

I also tried to give each rotator an id and to pass it as parameter to theRotator function - but it also didn't worked.
I'll appreciate for your advice:-)

Hey Dylan,

Thanks for your great rotator. I've incorporated the rotator into a prototype website for our CS Department, and it runs great on all browsers except IE. It's not running in the right location on IE. Any thoughts? Here's the url -

http://learn.roguecc.edu/computerscience/bbagwell/prototype/index.html

Thanks a bunch, Bob

Hi Dylan,
Thanks for creating this. It's really a great script. I've got it working correctly on my site but i'm having a problem with my nav menu that's position right above the images. I can't seem to get the subnav to appear above the images. I tried setting the z-index for both divs but that didn't seem to work. Any ideas?

Here is the working example:
http://ductrinh.com/bridgesolutions/index2.html

Thanks for any help you can provide.
-D

Thank you very much.
I want to use many images (about 70 images).

Does this script with 70 images slow down the loading of the page?
if yes, how can i avoid it?

Love the script, Is their a way to make it so it does not pause my embedded YouTube video every time it changes images?
Thank you

Jesse MT

Hey dukiejc, have you tried using --- .subnav, .subnav li{position:absolute} --- That might do it.

Jesse MT

Actually I edited the css live and this worked. it would need more work but this made the submenus show.

.subnav li{position:absolute;z-index:600;border:none;}

Jesse MT

Hi Bob, there's a couple of issues you have that make this difficult for IE I think.

1) You have the paragraph text which does not change, inside of the .rotator in your html.Move that all the way outside of the .acontent div. (bear with me here.)

2) Next, try using the forscore image in the .imageleft image as a background of .acontent and make .acontent position and fit where .leftimage is now. and you can get rid of the div and the h1 that is inside acontent. Layering images is needlessly difficult and laying your rotator over a background image is much easier and should remove conflicts.

So remove everything from the .rotator that doesn't rotate, remove h1 and image from .acontent and resize and reposition .acontent to have the forscor image as the background and only the .rotator inside of it(and .show inside of that). Then position your paragraph text outside that on the right. And all should be well.

If you need further help feel free to ask. I'm sure Dylan is about somewhere, I haven't seen him in a bit but he's probably around here somewhere.

Thanks - Great advice. All fixed now.

You guys are the best and I really enjoy your insights.

Hi - I am getting a conflict with this script and the LightBox 2 script.

http://www.huddletogether.com/projects/lightbox2/

Symptom - This script does not run (image rotation doesn't happen) and depending on the order the scrips are called in the html when you click on a LightBox image this script puts the initial image over the top.

TIA.

Glenn.

Jesse MT

Glen it would help if you gave a url to the page your working on and then maybe someone can find the issue and come up with a solution.

Hi Guys,
Excellent script. My question is how I would have this work to display the image rotator as the background image of the HTML class. I currently have a .php pulling from a folder of images to 100% display the image in the page while maintaining aspect ratio. How would you recommend I do this with this rotator? Create the divs as a stacked list just above the HTML of the page?

Thanks again!

Jon

Hi Dylan,

Thanks for making this script available! It is so simple to use. I am wondering if there is a way to set different time intervals for each image? Below is a link to the page I am working on.

www.costellocommunications.com/ecco2010

I have three images and would like the first image to be up for a shorter amount of time than the other two.

Thank you in advance for any help you can give me.

Sincerely,

Jessica

Just a quick note to say "Thank you" for this script and all your hard work - really appreciate it. I had been looking for a simple way to handle image transitions...and looking, and looking, and looking! This did the trick perfectly, so THANKS!

Dylan Wagstaff MT

Very cool NiSHo thank you for sharing.

I need it to be random but I just can't have it working.

Can you post the updated code please?

The page is here:
http://www.andreameirana.it/test/home2.html

Thank you!

Does this only rotate a foreground image? Can this be altered to rotate the background image of a div? I'd like the background to change automatically behind DIVs of enclosed text.

Could it be sequenced with a DIV of rotating text, so that they change at the same time?

This looks like something I could use for a project I'm taking on, but I'm not sure...

I'm not that good at this stuff, but I can't get this thing to work for love or money.

Everything seems to be in place, the first image loads up and then it doesn't rotate through the rest of the pix.

http://www.patrickhouston.com/tacair/index.html

Any help out there?

I have having some issue with the script and could use a bit of help. In Fire Fox 3.6.16 when the page loads the script does not. If you refresh the page or if you go to the navigation on the page and hit HOME it will. Works great in IE.

The page in question is

http://www.etmks.com

Any help would be much appreciated.

Thanks,
Andy

Thank you very much man :)) Very useful rotator!!!

NiSho, I have been trying to use your script to no success. Is there something missing in the code that needs to be done through out the site (i.e. any selectors you changed or more information we need to know when using this code).

It will be greatly appreciated. Thanks!

Thank you so much for this code. I am trying to do this effect on three div on a site. How do I change the code accordingly for each one?

Thank you for this code. It's working great. I just had one small question... I have 7 images displaying in a random order, is there a way to set this code up so that images are not repeated until all 7 have shown up once randomly?

LenP MT

Great demo, works like a charm as downloaded.

Here's the noob question...

when I try to split the script off into a .js file, no rotation, just displays the four images.

Any thoughts?

Cheers and thanks!

I'm having a similar problem as the last couple posts. The first image loads up fine, but it just doesn't rotate, like the javascript isn't being loaded or something. I've tried in FF4 and IE8.

Hi nisho, i saw your code, and works very well, nice code. but don't work on IE (chrome and firefox good). Appears an error and the image not rotate.

Error Message:
Line: 15
character: 2
code: 0

probably on: self = {

using http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js

I appreciate any help.
Thank.

Hi I have a problem this code seems to work well so far but for some reason everything worked up until I added the Java to my Head. Once I added the Javascript I changed the time for it to change every 1 second however despite it being uploaded and refreshed twice the image will not rotate. My site is http://www.shadowcore.co.uk/index.php could someone check the code and tell me that is wrong with this please.

Thanks for a great script! Is there a simple way to make the images pause on mouseover?

Thanks! :)

dogboy MT

Can someone please tell me which script to use to generate the images randomly from a folder? I've read through all the comments and there are a lot of varying ideas dating back to 2009 so I am not sure which one should be used or is most relevant now in 2011. I have a folder with about 150 images I would like to read from, and have the images rotate randomly each time a user visits the page. Thanks for your help.

Thanks for your great sample, it helps me a lot . How can I add a mouse over feature to it? I want to stop rotation by mouse over and start it again by mouse out.

Great Script. I am having an issue when the rotator first starts. I get the first image, then it repeats the first image, then a blank page, then it works properly. Any way to stop what is happening at startup?

Love this script. Worked perfect on one of my sites but when I put it on another site, the rotator speeds up each cycle. Both are wordpress. Must be clashing with some other code but I can't see what with. This site uses compression where as the first does not. This site has a jquery effect in it but nothing similar in the code for that. :/

Same complaint as a few others in recent comments - loads first image (remaining images appear to be layered underneath as expected according to Firebug), however the rotator fails to perform its intended function: rotating.

Tested on Firefox 5 & IE 7 - code copy-pasted direct from downloadable demo (which DOES work), so it seems this code has a conflict with something else in my WordPress install; whether that's a different version of JQuery than the one used in 2009 when this was created or another script on the page is beyond my ability to discern.

Was hoping to use this as a simple banner rotator, but I guess I'll have to keep looking.

- Ryan
www.theindiemachine.com

I ran into a problem when I tried using this script on a site I'm working on. If you open the document and view the rotator, it works fine. Until you open another tab (in Chrome or FireFox) and then switch back after several animations have passed. Then you see the animations you missed one after the other until it catches up with the current animation and then it goes back to normal speed. The jQuery api warns about using setTimeout. http://api.jquery.com/animate/#notes-0
Using the callback of the animate() function to set the timeout works nicely. I changed several things:

function theRotator(){
$('div.rotator ul li').css({opacity: 0.0});
$('div.rotator ul li:first').css({opacity: 1.0});
if ($('div.rotator ul li').length > 1) {
setTimeout('rotate()', 6000);
}
}

function rotate() {
var current = ($('div.rotator ul li.show')? $('div.rotator ul li.show') : $('div.rotator ul li:first'));
if ( current.length == 0 ) current = $('div.rotator ul li:first');
var next = ((current.next().length) ? ((current.next().hasClass('show')) ? $('div.rotator ul li:first') :current.next()) : $('div.rotator ul li:first'));
next.css({opacity: 0.0}).addClass('show').animate({opacity: 1.0}, 1000);
current.animate({opacity: 0.0}, 1000, function(){setTimeout('rotate()', 6000);}) .removeClass('show');

};

I added an if statement to check if there is more than one image and then I changed setInterval() to setTimeout(). To make the animation repeat, I added a callback function which calls rotate() after (and only after) the current animation has been completed. This fixes the backlog of animations and you don't see the animation trying to catch up. I hope this is helpful.

Thank you for sharing. Great work. :)

For those having conflicts within WordPress or other please google jQuery no conflict for a simple solution.

anders MT

Dylan and all, great code. I'm pretty novice at web design, but I'm trying to figure out how to incorporate this code into already located image container. The banner image of the site as it is right now is at http://eirikjohnson.com/Draft/

How would I go about incorporating the code into this existing image container? Thanks for any insight!

Re: anders the easiest way would be to change your container from #imageContainer to .rotator. If you need to keep your current id than you could switch every instance of div.rotator to div#imageContainer withing the script and css. Hope that helps.

I'm a noob. Can someone tell me how to link the javascript from and external file?

i've installed the image rotator on the homepage of my site: www.cherrysunset.com However, when i refresh or go back to the home page it seems to show all the images at once for a brief second. This problem is probably noticeable due to the face that my images have a transparent background, but if anybody could think of a way of changing the code to help me out, i would greatly appreciate it.

Is there a way to wrap text around the rotator?

Hey Dylan...cool script! I'm really new to this stuff, so my problem might have a simple solution for anyone that can help. The rotator looks great in Firefox, etc., but IE is having issues with the in-page placement. Can anyone help? I'd really appreciate it. This is the site http://www.lifeworks-international.com/indexrotate.php

Hi Dan, not sure what is causing the layout issue in your design but you could use a conditional ie statement as a fix. Where the adjusted css is only applied to ie. It is very simple and there are plenty of examples of how to do this on Google.

Jesse MT

Hi Dan,

1) Declare a doctype!
2) Put an opening HTML tag in your document!
3) VALIDATE your code!
4) Take all the javascript and css OUT of the html and put it in separate files that you call from your document.

Clean it up and validate it and that will probably fix your issue.

Jorge MT

Hi Dylan, first of all thank you very much for sharing the script: D
I wanted to know how I can do to make instead of going to the next image to the previous pass, to have if someone can help me, greetings from Mexico

Very useful rotator. thanks..

I want to stop rotation by mouse over and start it again by mouse out. Can any one help

I have a link around my images in the rotation and it works great except the last link is showing on the first image.

Anyway to solve this issue?
When the page loads it loads the pictures fine but attaches the last link to the first image.

Hi, I will like to know how to double or triple de rotator (2 or 3 set of photos) with different photos. I already try but only one photo rotate. A solution anyone?

jamesvoce MT

hi. I think your script is great. I'm strugglig to centre the images. When I try to apply display block with auto margins - the four images I'm using end up being displayed separately one on top of the other instead of fading over each other. Can you help with this? What am I doing wrong? Thanks

Great script! Is there a way to make the rotation stop after two cycles? And if so, is there a way to make it stop on a particular image?

Great script! Is there a way to make the rotation stop after two cycles? And if so, is there a way to make it stop on a particular image?

Christopher (or anyone) I would love to know what might be involved in creating 3 instances of the Rotator on a page... I was able to get one instance to work fine. Thinking that since it's done with class attributes, I could just put another list in another div, but the results are not good (only one set of images rotates) and it would be nice to have the start times and intervals different for each instance.

Thanks for a great bit of JS.

I have jQuery tabs and a slider on my page and looking to incorporate this rotator. I tried noConflict, but for the life of me I cannot get it working. Any help greatly appreciated.

jQuery.noConflict();
(function($){function theRotator(){$('div.rotator ul li').css({opacity:0.0});$('div.rotator ul li:first').css({opacity:1.0});setInterval('rotate()',5000);}
function rotate(){var current=($('div.rotator ul li.show2')?$('div.rotator ul li.show2'):$('div.rotator ul li:first'));if(current.length==0)current=$('div.rotator ul li:first');var next=((current.next().length)?((current.next().hasClass('show2'))?$('div.rotator ul li:first'):current.next()):$('div.rotator ul li:first'));next.css({opacity:0.0})
.addClass('show2')
.animate({opacity:1.0},1000);current.animate({opacity:0.0},1000)
.removeClass('show2');};$(document).ready(function(){theRotator();$('div.rotator').fadeIn(1000);$('div.rotator ul li').fadeIn(1000);});})(jQuery);

I get the initial image to fade in, but nothing happens after that. Any advice?

*Solved (duhh)
var j = jQuery.noConflict();

change instances of $ to j.

Rotator with lightbox would show over the lightbox image, easily solved by changing the zindex in css. Thanks, for this handy little tool!!

I wanted to thank you very much for all the work and support you've done on this -- I just used it to add rotating images to the banner on my Digital Filmmaking blog http://tachyonlabs.com/digital-filmmaking/ and it looks very nice!

Though I would also love to see you post a demo/source code for a multiple-instances version if you ever get around to it some day -- I was trying to have the banner images rotate individually instead of just in that bar of four at a time, but had some of the same problems as some of the other commenters above.

LOVE this! Like some others, I want to have 3 rotators on one page, with delayed starts for 2. I have 3 now, but only one shows at startup, then the other two only rotate through one time. The first one continues. Does someone have the code to make this work? Thanks!

Tracy MT

Brilliant!! Although I have a small problem, not sure if I'm reposting so sorry if I am. Anyway when I scrol down my page the rotating image moves too covering the content below as it goes, is there anyway to make sure the image stays put?? Thanks!

Love the script if it worked on IE!

Mine looks great in firefox and chrome, but only the top 50px or so of the entire image is showing up in IE. I have read this entire page trying to find a similar issue to no avail.

The site is http://millworksplace.com. Can someone please help me?

(Talk to me like I'm a 2 year old...)

How can the script be changed so that the images just rotate through once instead of cycling as an endless loop?

I have used this script with no problems, until I added the random image script to it.

The link is:
http://www.algonquinpark.on.ca/includes/common/sub_right_column_raffle2012.php

I have 3 windows and the 3rd one is now set up to use the following:

The script is in the same folder as the images to randomly rotate.

Problem is the image is only updated when you refresh the screen. The other two are not using a random script and they work fine.

Why is this happening?

Oh...this is the random script used:

/*

*/// Make this the relative path to the images, like "../img" or "random/images/".

// If the images are in the same directory, leave it blank.

$folder = '';

// Space seperated list of extensions, you probably won't have to change this.

$exts = 'jpg jpeg png gif';

$files = array(); $i = -1; // Initialize some variables
if ('' == $folder) $folder = './';;

$handle = opendir($folder);
$exts = explode(' ', $exts);
while (false !== ($file = readdir($handle))) {
foreach($exts as $ext) { // for each extension check the extension
if (preg_match('/\.'.$ext.'$/i', $file, $test)) { // faster than ereg, case insensitive
$files[] = $file; // it's good
++$i;
}
}
}
closedir($handle); // We're not using it anymore
mt_srand((double)microtime()*1000000); // seed for PHP $rand = mt_rand(0, $i); // $i was incremented as we went along

header('Location: '.$folder.$files[$rand]); // Voila!

Hi Dylan, awesome script... i've been using on a couple of sites for a while and it works great. One question i'm hoping you can answer though. I can see that you can delay the rotation of the images but is it possible to delay the initial running of the script? I have very little knowledge of jscript so this may be a stupid question but why I am asking is that I am wanting to reduce the initial load time of my site.. so i would like for the page to finish loading and then have the script run shortly after. For example, page loads and script runs after 10 seconds and then goes into the default 6 second rotation. Is this possible?

This is great - it's so simple and light. Thanks!

Hi Dylan,

I have tried using this script on my test site (http://testerkolts.weebly.com), so that I can place it on my full website (http://plymouthkoltsjfc.weebly.com) later, but the images don't rotate.

Please can you take a look and tell me what you think might be wrong?

Thanks

Jon

Wow! Thanks! Took me all of two minutes to implement. I think it took longer to google for your blog! You Rock!

Thanks for great script.

Doesn't anybody know how to display 3 random images vertical / horizontal at the same time ?
( they can't repeat )

I would be verry happy for any help

Great Slider....
But dear i have one issue.. when i am adding another slidr on same page, at that time 1st image of second slider is not visible....
Is their any way to show it....
Please help Me ..

Thanks,
Dev

Your script is really awesome and unbelievably easy to implement. Thank You very much!!!

But... I have one question: I tried to place on the website more then one rotator (independent - leading to different galleries) - and it doesn't works.

Is it possible at all? I'll appreciate for any help (even small hint)

Tomasz

sorry, can i have 2 or more div rotation and all div can rotate?

Thanks dude... Great work. Just needed a simple image slider and for me this is really works out.

I simplified it. jquery has good semantics so I hope people will understand it even without comments:

function rotate() {
$('#flip-box ul li').hide();
$('#flip-box ul li:first').show();
setInterval(function() {
var current = $('#flip-box ul li:visible');

if(typeof current.next().html() === 'undefined') {
current.fadeOut();
$('#flip-box ul li:first').fadeIn();
} else {
current.fadeOut().next().fadeIn();
}
},5000);
}

For all of you who haven't figured this out here is the Jquiry friendly code that will work with other scripts:

jQuery.noConflict();(
function($){
$(document).ready(function () {

function theRotator() {
//Set the opacity of all images to 0
$('div.rotator ul li').css({opacity: 0.0});

//Get the first image and display it (gets set to full opacity)
$('div.rotator ul li:first').css({opacity: 1.0});

//Call the rotator function to run the slideshow, 6000 = change to next image after 6 seconds

setInterval(test, 4000);

}

function test() {
//Get the first image
var current = ($('div.rotator ul li.show')? $('div.rotator ul li.show') : $('div.rotator ul li:first'));

if ( current.length == 0 ) current = $('div.rotator ul li:first');

//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'));

//Un-comment the 3 lines below to get the images in random order

//var sibs = current.siblings();
//var rndNum = Math.floor(Math.random() * sibs.length );
//var next = $( sibs[ rndNum ] );

//Set the fade in effect for the next image, the show class has higher z-index
next.css({opacity: 0.0})
.addClass('show')
.animate({opacity: 1.0}, 1000);

//Hide the current image
current.animate({opacity: 0.0}, 1000)
.removeClass('show');

};

$(document).ready(function() {
//Load the slideshow
theRotator();
$('div.rotator').fadeIn(1000);
$('div.rotator ul li').fadeIn(1000); // tweek for IE
});


});
})(jQuery);

Thanks to this for help:
http://stackoverflow.com/questions/9475288/uncaught-referenceerror-hello-is-not-defined

Dylan Wagstaff MT

Thanks for the simplified and no conflict versions above. Great Stuff!!

Posting Comment...

Leave a comment...

Tweet

what will you say?

Sponsors

hawaii web design demo demo