Creating A TextRotator In Javascript

0
358
Javascript TextRotator

Animation on web pages can be cool. In my case, I needed a little Javascript snippet to scroll quotes.

Yes, its been done before. Nothing new here. But just felt like a little Javascript coding for a pet project I had in mind.

The HTML

Simply create an empty div where you want the text to appear and give it the identifier name of quotetext.

<div id="quotetext">
</div>

The Javascript

Insert this script anywhere in your page, preferrably right under the empty div.

  1. <script type="text/javascript" >
  2. var myquotes = new Array(
  3.   '"Its like your own virtual soap box" - Cindy Fuller, Texas',
  4.   '"Just mooooooo!" - Evan Gonzales, California',
  5.   '"Udderly fantastic!" - Adam Price, New York',
  6.   '"Informative, useful." - John Almos, Nevada',
  7.   '"Stand up and be heard!" - Anna Olsen, Idaho',
  8.   '"A friendly, open, social community." - Gary Patterson, California');
  9.  
  10. function rotatequote() {
  11.   thequote = myquotes.shift();
  12.   myquotes.push(thequote);
  13.   document.getElementById('quotetext').innerHTML = thequote;
  14.   t=setTimeout("rotatequote()",6000);  // 6 seconds
  15. }
  16.  
  17. rotatequote();
  18. </script>

So what we are doing here is creating a Javascript array of string quotations. We call the function, rotatequote() which takes the first item off the quotation array and assigns it to the variable, thequote.
We then push this string to the back of the array, essentially rotating it. Then, assign the quotation we just popped to the HTML div. Finally, we set a timer which calls the rotatequote function every 6 seconds.

The Demo

Save the code below off to a HTML document and then bring it up with a browser.

  1. <!DOCTYPE html>
  2. <html>
  3. <head><title>Test TextRotator</title></head>
  4. <body>
  5.   <div id="quotetext">
  6.   </div>
  7.   <script type="text/javascript" >
  8.     var myquotes = new Array(
  9.     '"Its like your own virtual soap box" - Cindy Fuller, Texas',
  10.     '"Just mooooooo!" - Evan Gonzales, California',
  11.     '"Udderly fantastic!" - Adam Price, New York',
  12.     '"Informative, useful." - John Almos, Nevada',
  13.     '"Stand up and be heard!" - Anna Olsen, Idaho',
  14.     '"A friendly, open, social community." - Gary Patterson, California');
  15.  
  16.     function rotatequote() {
  17.       thequote = myquotes.shift();
  18.      myquotes.push(thequote);
  19.      document.getElementById('quotetext').innerHTML = thequote;
  20.      t=setTimeout("rotatequote()",6000);  // 6 seconds
  21.     }
  22.     rotatequote();
  23.   </script>
  24. </body>
  25. </html>

Use this in your web pages and WordPress blogs to make them a little more interesting.

Of Interest