Marquee not displaying all text - cutting off at different points

methuselah picture methuselah · Aug 10, 2013 · Viewed 7.3k times · Source

My marquee doesn't seem to be displaying all the text I have placed in my div. It always gets cut off at a certain point. Any idea how I can get it show all the text?

This is my code so far (demo at http://jsfiddle.net/yLwhe/)

HTML

<div id="marquee">They came down the village, crossing ghostly forests, almost falling apart. Their bags were full: garlands, amethysts, gold, frankincense, myrrh. Incredible strings arrived with them: heavenly sounds drew water from marble stones, provoking visions never seen before. Who brought those tired magicians? Why had such a music enchanted our sordid souls? Was no answer available? Did we need one? Voices overheard told of incredible tales: children following mice, drowning, dead. Fear turned us into shivering salty statues, unable to look back. Many years later, explorers ventured and found this tiny town, every inhabitant eternally still, imprisoned forever by strange chords.</div>

CSS

#marquee {
    color: #000;
    height: 16px;
    padding-bottom: 5px;
}

JS

$(function() {

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

    // wrap "My Text" with a span (IE doesn'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"

    marquee.wrapInner("<div>");
    marquee.find("div").css("width", "200%");

    var reset = function() {
        $(this).css("margin-left", "0%");
        $(this).animate({ "margin-left": "-100%" }, 10000, 'linear', reset);
    };

    reset.call(marquee.find("div"));

    });

Answer

techfoobar picture techfoobar · Aug 10, 2013

Your original code assumed that the 100% width <span> (i.e. 50% inside the 200% width <div>) will accommodate the entire text.

I've modified it to actually calculate the width required by the string and then use that to do the animation.

Check this modified version: http://jsfiddle.net/yLwhe/5/

i.e.:

...
marquee.find("span").css({ ... }); 

// get the actual used width
var w = marquee.find("span").width();

...
var reset = function() {
    $(this).css("margin-left", "0");

    // use calculated width for animation.
    $(this).animate({ "margin-left": "-"+w+"px" }, 40000, 'linear', reset);

};