September 7th, 2007

How to rotate an image or text with JavaScript & DHTML

So I need to rotate an image every few seconds on a homepage of a site I'm building. I looked around for some pre-built code that I could do this with, and I found a few functions. I picked the one I like the best, and I've modified it to my needs. This JavaScript code lets you define an array of HTML items (so you could use images, text, links, you name it!), and loop through the array. I added the variable for you to define how many seconds between rotation. Here's the JavaScript function, it will run automatically on the page load event. Place it in between your <head></head> tags.


<script language="JavaScript1.2">

var howOften = 2; //number often in seconds to rotate
var current = 0; //start the counter at 0
var ns6 = document.getElementById&&!document.all; //detect netscape 6

// place your images, text, etc in the array elements here
var items = new Array();
    items[0]="<img src='monkey.gif' border='0'>"; //an image
    items[1]="<a href='#'><img src='monkey.gif' border='0'></a>"; //a linked image
    items[2]="Text without a link";
    items[3]="<a href='#'>Text with a link</a>";
    items[4]="<a href='#'><img src='monkey.gif' border='0'> Text and image with a link</a>";

function rotater() {
    if(document.layers) {
        document.placeholderlayer.document.write(items[current]);
        document.placeholderlayer.document.close();
    }
    if(ns6)document.getElementById("placeholderdiv").innerHTML=items[current]
        if(document.all)
            placeholderdiv.innerHTML=items[current];

    current = (current==items.length) ? 0 : current + 1; //increment or reset
    setTimeout("rotater()",howOften*1000);
}
window.onload=rotater;
//-->
</script>

Alternately, if you like simpler code, and you don't care about the .017% of users still using Netscape 6, you can use this JavaScript function for rotater:


function rotater() {
    document.getElementById("placeholder").innerHTML = items[current];
    current = (current==items.length-1) ? 0 : current + 1;
    setTimeout("rotater()",howOften*1000);
}

And here's the placeholder layers that you need to add to your HTML page to rotate the content in:


<layer id="placeholderlayer"></layer><div id="placeholderdiv"></div>
Share

39 Responses to ' How to rotate an image or text with JavaScript & DHTML '

Subscribe to comments with RSS or TrackBack to ' How to rotate an image or text with JavaScript & DHTML '.

  1. mark said,

    on September 13th, 2007 at 11:39 am

    Hmmm, I've implemented your code, but it doesn't seem to be working. Any ideas?

    var howOften = 5; //number often in seconds to rotate
    var current = 0; //start the counter at 0
    var ns6 = document.getElementById&&!document.all; //detect netscape 6

    // place your images, text, etc in the array elements here
    var items = new Array();
    items[1]=""; //a linked image
    items[2]="";
    items[3]="";
    items[4]="";
    items[5]="";

    function rotater() {
    if(document.layers) {
    document.placeholderlayer.document.write(item[current]);
    document.placeholderlayer.document.close();
    }
    if(ns6)document.getElementById("placeholderdiv").innerHTML=item[current]
    if(document.all)
    placeholderdiv.innerHTML=item[current];

    current = (current==items.length) ? 0 : current + 1; //increment or reset
    setTimeout("rotater()",howOften*1000);
    }
    window.onload=rotater;
    //–>

  2. Justin Cook said,

    on September 13th, 2007 at 11:44 am

    Do you have any javascript error you can send over?

    I see an error in my code though, the items array is referred to as item later on. I'll change my code, you can copy and paste the new one.

  3. Richard said,

    on September 17th, 2007 at 10:04 pm

    Hello, i just want some help, i'm new with wordpress so, can you please tell me what code to use to put google's ads in the lift like yours?
    thanks a lot ok.

  4. Justin Cook said,

    on September 18th, 2007 at 11:28 am

    Look for a wordpress plugin called Adsense deluxe

  5. Dan said,

    on October 17th, 2007 at 4:54 pm

    Any chance there's an easy way to put additional placeholder layers on the webpage which could pull from the same script, but start at different points in the rotation?

    The end result would be that all images are visible at one time, they'd just appear to cycle through different positions on screen.

    Thanks in advance for any suggestions.

  6. Justin Cook said,

    on October 17th, 2007 at 6:32 pm

    Yes. You would have to just add the additional placeholders, and then create a loop which sets the inerHTML to the last called item + 1.

    So, if there were 5 placeholders, the first gets the content for item[0], the second for item[1], etc. The next time through, the first gets the content for item[1], the second for item[2].

  7. Dan said,

    on October 18th, 2007 at 4:14 pm

    Thanks Justin, I'll try that out. . . I haven't used JavaScript before, so this is all kind of new.

  8. Cameron said,

    on December 11th, 2007 at 6:00 pm

    After the items reach the end, I get "undefined" as a text string. I started by simply copying and pasting the example code above. Everything works except no matter what I do, "undefined" shows up at the end of the loop / after the last item. Thoughts?

  9. Justin Cook said,

    on December 12th, 2007 at 8:10 am

    If you send me the URL to check it out, maybe I could help you.

  10. BLiZZ said,

    on January 26th, 2008 at 5:59 pm

    the reason you get an undefined at the end is a slight misstep in the code. You are telling th script that current is either equal to 0 or itself+1. The length then runs to the end and repeats, however it is still adding 1 to the length when it is at the end ( in this case [4] ) and thus looking for [5]. All you have to do is edit the item.length to increment -1 as the total length.

    This line:

    current = (current==items.length) ? 0 : current + 1; //increment or reset

    should be

    current = (current==items.length-1) ? 0 : current + 1; //increment or reset

    Enjoy :)

  11. sudhakar said,

    on April 28th, 2008 at 1:07 am

    Hi,This works very nice, but how to avoid the flickering of image when i rotate the image

  12. shannon said,

    on June 16th, 2008 at 10:04 am

    Can this code be altered to have the images rotate randomly? Thanks, Shannon

  13. Irina said,

    on July 14th, 2008 at 5:46 am

    I think to add fade effect on this rotation to avoid images flickering, but so far I haven't figure out how to do that. I achieved fade effect only for text or only for images but not for both at the same time. If anybody knows how to fade images and text at the same time, please let us know.

  14. Andrea said,

    on October 24th, 2008 at 10:39 am

    Thank you for this code, I have found it very helpful. I have used it on the home page of a website I work on for a university. However, I am running into the same problem someone else has mentioned with "undefined" appearing at the end of the rotation. I used the change in code which you mentioned, and I have no errors, but am still seeing the "undefined" at the end of the rotation. Any ideas?

  15. Sushama said,

    on January 5th, 2009 at 5:21 am

    Thank you for this code….it's very nice and works fine. :) Keep it up

  16. Raj said,

    on January 7th, 2009 at 4:44 am

    First of all Thanks Justin for this awesome piece of work!!

    about the flickering of the image : It happens when you try to load a bigger image in a smaller area.. e.g if you are trying to fit a image of size 1000*500 in a 200*100 area, the flicker occurs. At least this is what i experienced and solved it by using proper size image

    about the 'undefined' error, the solution provided by BLIZZ is perfect. If u guys still have that error then please check the array if they are named in proper sequence..
    the code is almost perfect.

  17. Arshad said,

    on January 26th, 2009 at 6:09 am

    I want to use "2" image rotator in same page… but unable to do so with your code.. Please help.. single is working fine…

  18. Karin said,

    on February 2nd, 2009 at 2:39 pm

    Hi Justin, thanks for the script! I was just wondering if it was possible to add a fade in, fade out effect to this? Someone mentioned above that they kinda figured it out but didnt give the code… thanks!

  19. Np said,

    on February 5th, 2009 at 12:50 am

    thanx for this code, it works very well. did any of you add fade effect to the text? it will make the transition more fluid in relaxing for the eyes. if u have, please post.

    cheer!

  20. Patryk said,

    on February 10th, 2009 at 7:35 am

    Hi guys.
    Everything works corectly, but I want to have separated placeholderdiv in different parts on my singular page of my website. Is it possible?

  21. Katy said,

    on March 27th, 2009 at 7:27 am

    Thanks for this.

    I'd tried to do something similar but ended up getting stuck in a recursive loop – your Array idea solved the problem a treat!

  22. Sanjay said,

    on April 23rd, 2009 at 7:57 am

    Hi All
    I would like to put the google ads script in the place of text content like
    items[5]="–google Ads script–";
    when i try to do this it's through the Error as below
    ———————————————————————–
    "; function rotater() { if(document.layers) { document.placeholderlayer.document.write(items[current]); document.placeholderlayer.document.close(); } if(ns6)document.getElementById("placeholderdiv").innerHTML=items[current] if(document.all) placeholderdiv.innerHTML=items[current]; current = (current==items.length) ? 0 : current + 1; //increment or reset setTimeout("rotater()",howOften*1000); } window.onload=rotater;
    ————————————————————————
    anybody help me
    Thanks in Advance

  23. Bobby said,

    on May 31st, 2009 at 3:50 pm

    If someone knows how to have the text (don't need images) rotate and fade can you post the code or send it to me. Much appreciated! Thanks

  24. don said,

    on June 23rd, 2009 at 3:17 pm

    Excellent script. It worked 3rd time round after removing the typos I made!

  25. John said,

    on November 18th, 2009 at 6:08 am

    i want code for rotating a word or some text around fixed axes in clock wise direction. can you able to help me out…?

  26. satya said,

    on November 30th, 2009 at 3:58 pm

    Hello Justin,

    This is working perfect with IE not with Google Chrome. Any idea how to solve it?

    Thanks
    Satya

  27. Domenica said,

    on December 3rd, 2009 at 3:40 pm

    ok… so the code is what I am looking for, but what is needed if I wanted to add different font styles, size and color to the different text items? Thank you.

  28. Kevin said,

    on January 13th, 2010 at 2:42 am

    Hi Justin,

    This piece of code sounds exactly what I am looking for. I want to serve text ads on my website initially from one location, but may consider other placeholders later to promote my affiliate members URLs for them. I also want the code to display different links to different visitors on my site.

    Example:

    If I had 100 text links and 100 people visited a page on my site simultaneously (or within seconds of each other), I want the code to deliver all 100 links (a different one to each visitor) – is this possible with your code?

    I've used Serif Webplus X2 to build my site, but I've fallen at the first hurdle with the above code in that it doesn't appear on my site at all.

    See the code snippet below:


    Welcome to Mobilbo – Your Work at Home Business Resource











































    var howOften = 2; //number often in seconds to rotate
    var current = 0; //start the counter at 0
    var ns6 = document.getElementById&&!document.all; //detect netscape 6

    // place your images, text, etc in the array elements here
    var items = new Array();
    items[0]=""; //an image
    items[1]=""; //a linked image
    items[2]="Text without a link";
    items[3]="Text with a link";
    items[4]=" Text and image with a link";

    function rotater() {
    if(document.layers) {
    document.placeholderlayer.document.write(items[current]);
    document.placeholderlayer.document.close();
    }
    if(ns6)document.getElementById("placeholderdiv").innerHTML=items[current]
    if(document.all)
    placeholderdiv.innerHTML=items[current];

    current = (current==items.length) ? 0 : current + 1; //increment or reset
    setTimeout("rotater()",howOften*1000);
    }
    window.onload=rotater;
    //–>

    <!–
    body {margin: 0px; padding: 0px;}
    a:link {color: #8d8d8d;}
    a:visited {color: #ffffff;}
    a:hover {color: #8d8d8d;}
    a:active {color: #8d8d8d;}

    And advice you can give to get this up and running on my site will be very helpful. And.. of course I will be happy to link back to your site.

    Thanks in advance,

    Kevin

  29. Kevin said,

    on January 13th, 2010 at 2:44 am

    ps.. some of the code seems to have disappeared from the above post. Please mail me at kevin@mobilbo.com and I'll mail you the code.

    Thanks again,

    Kevin


  30. on March 25th, 2010 at 1:11 pm

    Can you add a sample of the code on this page? That would be awesome. Thanks.

  31. 5Apples said,

    on June 15th, 2010 at 10:43 pm

    I've been trying to figure out what I'm doing wrong with this code. I'm using FrontPage 2003. I'm just trying to rotate some text for my testimonials box. Here is what I've done:

    var howOften = 2; //number often in seconds to rotate
    var current = 0; //start the counter at 0
    var ns6 = document.getElementById&&!document.all; //detect netscape 6

    // place your images, text, etc in the array elements here
    var items = new Array(7);
    items[0]=""I was able to get off all my medications."~Brad";
    items[1]=""A very great place that is truly Blessed by God."~John";
    items[2]=""We just thank God for giving the knowledge and wisdom to the staff."~Mrs. Martha";
    items[3]=""Thank you team for the clear demonstration of what to do."~Jack";
    items[4]=""It was one of the best decisions I have ever made!"~ Linda"";
    items[5]=""Words can't explain how thankful I am for my new lease on life."~Pat F.";
    items[6]=""I witnessed guests of all ages find victory and relief to their health issues."~Renee";

    function rotater() {
    if(document.layers) {
    document.placeholderlayer.document.write(items[current]);
    document.placeholderlayer.document.close();
    }
    if(ns6)document.getElementById("placeholderdiv").innerHTML=items[current]
    if(document.all)
    placeholderdiv.innerHTML=items[current];

    current = (current==items.length-1) ? 0 : current + 1; //increment or reset
    setTimeout("rotater()",howOften*1000);
    }
    window.onload=rotater;
    //–>

    and I have included the following code where I want the text to rotate:

    I've tried this code without the html markup (ie: etc) with no success.

    Thanks for any help you can give, it will be very appreciated.

  32. 5Apples said,

    on June 15th, 2010 at 10:46 pm

    sorry, it dropped my markup code, so it shows a double quote.

    Am I missing a numerical qualifier somewhere that would match up with the new Array[7]?

  33. 5Apples said,

    on June 15th, 2010 at 10:48 pm

    Looks like it dropped quite a bit of script too. I'll be glad to email it or send you to the test page link.

  34. chrisk said,

    on January 3rd, 2011 at 11:42 am

    you are the man, needed something quick and easy to pop into a site for someone. i'm a designer, not really a programmer, and this was very easy and straightforward. thank you so much!!!

  35. Peter said,

    on February 25th, 2011 at 10:09 am

    Justin — I am working on a new website upgrade and was looking for the ability of rotating text like what you provided above. It worked great…until I added back the countdown timer script we run on the top of the page. So, with your script the old script doesn't work and vice a versa.:-( Here is the page that I'm working on: http://hyperflite.com/new_hyperflite_website/index.html. I'm sure you can see your scrip working halfway down the page. If you want to see our script working, you can see it on our home page here: http://hyperflite.com. I assume there is a conflict, but I don't know anything about java scripting. Can you provide a solution? Your script is contained in the header, but the countdown script is linked. Thanks. Peter

  36. Peter said,

    on February 26th, 2011 at 9:33 am

    Justin—Sorry for the typo on scripts in my last post, unfortunately, there is no way for me to correct it or delete it after it's been submitted.:-(

    I tried a few things on the countdown script but, not knowing anything about Java, failed to get it to work, so I did the next best thing…looked for a different countdown timer.:-)

    I found one that seems to work with your script, and, if you are interested, here it is…

    http://www.hashemian.com/tools/javascript-countdown.htm

    Thanks again for your script. Just what I was looking for.

  37. Osyrys said,

    on March 17th, 2011 at 2:19 am

    This is awesome. I narrowed it down a little cause I only needed 3 image links rotating, and somewhere it's reading a 4th and rotating the three images and then blanking the 4th with "undefined" at the top… Any thoughts? All I did was remove the items[0]=""; lines that I wasn't using… Thanks so much in advance for any help!!

  38. KGoepel said,

    on November 5th, 2011 at 10:34 am

    I am attempting to use this code to rotate 3 text testimonial quotes but it keeps coming up with a fourth with "undefined" text. Any idea what I may be doing wrong?

  39. KGoepel said,

    on November 5th, 2011 at 11:00 am

    Sorry! Eventually found it in the thread and now works perfectly, thank you!

Leave a reply

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word