Scrolling image marquee javascript

MochaMoroll picture MochaMoroll · Dec 7, 2011 · Viewed 9.9k times · Source

I currently want to make a marquee of several images, but my code only allows one. Do you know any way I could add several images to this code? (I have already tried adding the images directly into the div element within the body - it doesn't work.)

   <style type="text/css">
   <!--
    #container {
    background-image: url(images/avycopy.jpg), url(images/5mwmcp.jpg);
    height:428px;
    width:284px;
    background-repeat:repeat-x;
    background-size:284px 428px;
    background-position: top left, top right;
    }
    -->
    </style>

    <script type="text/javascript">
    <!--

    var p=0;
    var speed=20;   // vary this to suit, larger value - slower speed

    window.onload=function() {
    gallery();
    }
    function gallery() {

    document.getElementById('container').style.backgroundPosition=p+'px 0';

    p--;    //change this to p-- for right to left direction

    setTimeout('gallery()',speed);
    }
    //-->
    </script>

Answer

meustrus picture meustrus · Sep 6, 2012

I've put such a slider together for you. No frameworks necessary, although there are some cross-browsers concerns I haven't dealt with (including IE before version 8 dealing with scrollWidth differently).

First, arrange the code like so:

<div id="marquee-container"
 ><span><img src="http://www.dragonfly-site.com/graphics/20-free-dragonfly-clip-art-l.jpg" /></span
 ><span><img src="http://0.tqn.com/d/macs/1/0/2/M/-/-/clipprojectchristmas_400x400.png" /></span
></div>

Add some CSS like this:

#marquee-container {
 width: 500px; /* or whatever you want */
 margin: 0 auto; /* centers it */
 overflow: hidden;
 white-space: nowrap;
}

Now all that should remain is javascript to keep it moving. This will jump back to the beginning once it scrolls all the way; it should look continuous because it duplicates all the images at the end:

(function(window, document, undefined) {
 var spaceinterval = 1;
 var timeinterval = 10; // `speed`
 var max;
 var firstrun = true;
 // Interval function:
 var gallery = function() {
  var elem = document.getElementById("marquee-container");
  if (elem) {
   if (firstrun) {
    max = elem.scrollWidth;
    // Clone the children of the container until the
    // scrollWidth is at least twice as large as max.
    while (elem.scrollWidth < max * 2) {
     var length = elem.children.length;
     for (var i = 0; i < length; ++i) {
      elem.appendChild(elem.children[i].cloneNode(true));
     }
     break;
    }
    firstrun = false;
   }
   if (elem.scrollLeft >= max) {
    elem.scrollLeft -= max;
   } else {
    elem.scrollLeft += spaceinterval;
   }
  }
 };
 window.setInterval(gallery, timeinterval);
})(window, document);

In a jsfiddle