Creating a text rotator with jQuery

quote

jQuery is appropriately described as the “write less, do more” library. Few lines of code, if written appropriately, can produce wonderful tools or utilities.

In this article we will create a simple text rotator (or banner rotator whatever you want to call it). Simply put, there will be a placeholder which will have multiple quotations written inside it. These quotations will be displayed one by one with a fading effect. Have a look at the demo to see how it will look like.

View Demo

Now that you have seen the demo and you find it interesting enough, here is how to create it.

Write the following html which will create a container div with id quotes. Inside this div, create multiple divs, each of which will hold a quotation and assign a css class textItem to them.

Except for 2 things, you can style the elements as per your wish. First, div with id quotes should have position as relative and each textItem should have position set to absolute. Absolute positioning for quotations will ensure that they are stacked on top of each other. This way if we fade out a quotation and fade in the next one, it will give desired effect.

Complete markup will look like the following.

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml">
 <head>
<title>jQuery Text Rotator - by Vijay Joshi | vijayjoshi.org</title>
<style type="text/css">
 body
 {
   background-color:#BCDFDB;
   color: #025C7F;
   font-family:verdana,arial;
 }
 #quotes
 {
   margin:0;
   padding:100px;
   font-size:20px;
   position:relative;
 }
 .textItem
 {
   position:absolute;
   display:none;
 }
 a
 {
   color:#000;
   font-size:15px;
 }
 </style>
 </head>
 <body>
     <div id="quotes">
         <div>Before turning to those moral and mental aspects of the matter which
present the greatest difficulties, let the inquirer begin by mastering
more elementary problems.
         </div>

         <div>How often have I said to you that when you have eliminated the
impossible, whatever remains, however improbable, must be the truth?
         </div>

         <div>It is a capital mistake to theorize before one has data.
Insensibly one begins to twist facts to suit theories, instead of
theories to suit facts.
         </div>

         <div>We must fall back upon the old axiom that when all other contingencies
fail, whatever remains, however improbable, must be the truth.
         </div>
     </div>
 </body>
</html>

Now just before the body tag closes, include jQuery and next to it write the actual code that will put life to our quotations.

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/
jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
 $(document).ready(function()
 {
     setupRotator();
 });
 function setupRotator()
 {
     if($('.textItem').length > 1)
     {
         $('.textItem:first').addClass('current').fadeIn(1000);
         setInterval('textRotate()', 3000);
     }
 }
     function textRotate()
     {
         var current = $('#quotes > .current');
         if(current.next().length == 0)
         {
             current.removeClass('current').fadeOut(1000);
             $('.textItem:first').addClass('current').fadeIn(1000);
         }
         else
         {
             current.removeClass('current').fadeOut(1000);
             current.next().addClass('current').fadeIn(1000);
         }
     }
</script>

First of all, function setupRotator is called on document ready. This function will hide all textItem elements. Then it finds the first textItem and adds a class current to it. current class will help us identify which quotation is currently being displayed. After applying the class current it uses the fadeIn function to display the first item.

Now comes the key point. Using JavaScript function setInterval, set a function textRotate() to execute every 3 seconds.

Here is what textRotate function does.

  • get the quotation with class current - This will be currently visible element on page
  • Check if this quotation has any element next to it or not
  • If not, this means it is the last quotation. Therefore, remove the class current from it and use fadeOut function which will hide it after 1 second. Find the first quotation, apply class current to it and use fadeIn to make it visible
  • If a quotation is found next to current quotation, remove the class current from it and use fadeOut to hide it. Apply class current to the next element and make it visible using fadeIn

We have used value 1000 at all places in fadeIn and fadeOut which means the animation will take 1 second to complete, providing the desired effect.

Do not forget to view page source for full code.

I will soon convert it to a jQuery plugin so that it becomes easy to use it on pages without any change to code.

20 thoughts on “Creating a text rotator with jQuery

  1. Pingback: Tweets that mention Creating a text rotator with jQuery | vijayjoshi.org -- Topsy.com

  2. Harish

    Nice article Vijay. Just one bit correction. In the code given in the article you have forgot to give “textItem” class to each DIVs.

    Reply
  3. Stan

    Good job but if I want to add a few text rotator i one page, there’s error – every divs are in the same position. How to do this rotator for example:

    Before turning to those

    How often have I

    lorem ipsum – content of page

    Before turning to those

    How often have I

    Reply
  4. edsign

    Thanks for sharing!

    It’s simple, nice and clean code!

    However, I changed the code a little bit but couldn’t figure out, you might be able to help me a little bit?

    I put text-align to center, and when it fades out and fades in the next text the position has moved from down to up. How can I fixed the position?

    Thanks in advance! I really appreciate it!

    Reply
  5. Jacob Edmond Kerr

    Wondering why no one has mentioned the fact that if this script has been running for more then 15 minutes all the text runs into each other. I have not found a fix for this yet.

    Reply
  6. Alan

    Is there a simple way to add previous and next buttons? Thanks for the post! It was a great article!!

    Reply
  7. Niels Larsen

    Is it possible to set individual time on each DIV?
    Short text – short time, long text – long time.

    Straightforward code – love it :-D

    Reply

Leave a Reply