DHTML / JavaScript Marquee

Any one who is keen about writing valid (X)HTML knows that the marquee tag is not part of the HTML specification. So what is one to do when in need of a scrolling marquee within a valid html document? The following code demonstrates how to create a valid marquee using html, css, and javascript.

Enter the following into your HTML document:


<div id="newsticker">
<div id="marquee">•Item 01 •Item 02 •Item 03</div>
</div>

Place the following into your CSS:


#marquee {
position:relative;
/*marquee left should have the same value as newsticker width*/
left:400px;
overflow:visible;
width:auto;
float:left;
white-space:nowrap;
}
#newsticker {
/*newsticker width should have the same value as marquee left*/
width:400px;
height:20px;
border-width:thin;
border-style:solid none;
border-bottom-color:#999999;
background:#FFFFFF;
margin:auto;
position:relative;
left:auto;
clear:both;
overflow:hidden;
}

Finally add the following between your script tags or into your external JavaScript file:

function startSlide(){
if(document.getElementById("marquee")){
slide();
}else{
setTimeout("startSlide()",1000);
}
}
function slide(){
/*increase timeX to slow speed, decrease it to go faster*/
var timeX=32;
var newsTick=document.getElementById("newsticker");
var myMar=document.getElementById("marquee");
var newsTickLeft=newsTick.offsetLeft;
var myMarLeft=myMar.offsetLeft;
var myMarWidth=myMar.offsetWidth;
var timer=setTimeout("slide()",timeX);
function speedTime(){
slide();
}
function slowTime(){
clearTimeout(timer);
}
newsTick.onmouseover=slowTime;
newsTick.onmouseout=speedTime;
if (myMarLeft&amp;gt;-myMarWidth){
myMar.style.left=myMarLeft-1+"px";
}else{
myMar.style.left=newsTick.offsetWidth+"px";
}
}
window.onload = startSlide();

Click the following link to see it in action:
Example

Get the source files by using the link below:
Download

  • Delicious
  • Google Buzz

Related posts:

  1. Create a Rollover Class with JavaScript



© Wardell Design 2010
Entries (RSS) and Comments (RSS).