Seamless jQuery Marquee?

Pez Cuckow picture Pez Cuckow · Jan 26, 2010 · Viewed 31.9k times · Source

Is it possible to create a 100% seamless marquee in jQuery (or just javascript but jQuery prefered)?

I've made a simple marquee that moves left until it is off the screen then simply jumps (when out of view) to the right and starts again. However I would love it to not have the wait.

The only way I could think of doing this would be to duplicate the text and put it after the first text, then swap them round again. However I have no idea how to implement this in jQuery, I've been looking at jQuery's .clone() but can't get it working correctly, everything jumps.

Any ideas?

Thanks for your time,

Answer

Joel picture Joel · Jan 26, 2010

Given the following markup:

<div id="marquee">My Text</div>

For the duplication, I'd do something like this:

$("#marquee").wrapInner("span"); // wrap "My Text" with a new span
$("#marquee").append($("#marquee span").clone().hide()); // now there are two spans with "My Text"

Moving and swapping the spans is pretty easy. Here's a fully functional example:

$(function() {

    var marquee = $("#marquee"); 
    marquee.css({"overflow": "hidden", "width": "100%"});

    // wrap "My Text" with a span (old versions of IE don't like divs inline-block)
    marquee.wrapInner("<span>");
    marquee.find("span").css({ "width": "50%", "display": "inline-block", "text-align":"center" }); 
    marquee.append(marquee.find("span").clone()); // now there are two spans with "My Text"

    // create an inner div twice as wide as the view port for animating the scroll
    marquee.wrapInner("<div>");
    marquee.find("div").css("width", "200%");

    // create a function which animates the div
    // $.animate takes a callback for when the animation completes
    var reset = function() {
        $(this).css("margin-left", "0%");
        $(this).animate({ "margin-left": "-100%" }, 3000, 'linear', reset);
    };

    // kick it off
    reset.call(marquee.find("div"));

});

See it in action.

Disclaimer:

I don't recommend this for any professional website. However, it might be useful if you're trying to reproduce a retro 1990's look.