I am developing a site and on one of the pages I added an updateable (from a custom CMS) scrolling text banner.
The client was really impressed and asked me to make one on the front page as well.

I thought of sharing this because although to make a scrolling text banner in javascript is quite easy is still producing a good effect (when not overused) specially when the text can be updated at will from a CMS.

Here is the code that does most of the work:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
 * @param elem Element (div) containing the text to scroll
 */
function scrollText(elem)
{
    if (elem) {
        var str = elem.innerHTML;
        // get the first character of the string
        var firstChar = str.substr(0,1);
        // get the whole text except the first character
        var sub = elem.innerHTML.substr(1);
        // attach the first character at the end of the string and replace the element content
        elem.innerHTML = sub.concat(firstChar);
    }
}

The above function is called at regular intervals using the following line of code:

setInterval('scrollText(document.getElementById("text-to-scroll"))', 333);

Unzip the following file: scrolling.html.zip (999 bytes) to see the complete example.