Create a Scrolling Text Box using JavaScript

This can be easily done using jQuery or similar JavaScript libraries. But sometimes you may choose not to load the whole library for a simple task like scrolling text.

Javascript scrolling text function

Create a javascript function and place it either inside the element using < script > tag, or inside a separate javascript file.

//Define a variable (pos) to store the current scroll position.
var pos = 100;

function Scroll(){
    //get the id of the scrolling text box.
    obj=document.getElementById('scrolltextlayer');
    //subtract 1 from pos and check pos value using offsetHeight, which retrieves the height of the object relative to the layout.
    pos -=1;

    if(pos < 0 - obj.offsetHeight+130) return;
    //set a new height value using JavaScript style object.
    obj.style.top=pos;
    //finally the function calls itself using a timeout..
    window.setTimeout( "Scroll();" ,  30);
}

HTML

HTML is pretty simple:

  1. Create outer div that will act as a “frame”
  2. Create inner (scrolling) div
OUTER DIV
INNER DIV

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Cras hendrerit mauris eget nunc. Proin dapibus eros in quam. Nunc nulla nunc, nonummy auctor, scelerisque non, cursus et, leo. Nullam egestas nulla feugiat orci. Integer lorem sapien, ullamcorper dapibus, cursus eu, sagittis vel, dolor. Mauris tincidunt, magna in congue bibendum, sem quam tincidunt tortor, in consectetuer turpis odio a libero. Link to scroll again Scroll again

END INNER DIV

END OUTER DIV

Implementation

Just call the function from “onload” attribute inside the tag.

< body onLoad="Scroll();">

 

Related Posts: