appi2012 appi2012 - 1 year ago 68
Javascript Question

CSS/JQuery powered sideways scrolling text on hover

I have a twitter feed on a website I run. However, it gets cut off on small screens. I have a bar tall enough for 1 line of text in which I have the latest tweet. I want the tweet to ellipsize or fade out at the end if it is too long. But on hover, I want the text to slide slowly to the left, thus exposing the hidden part.

This effect is used on the iPod classic when you highlight a song that has a title that is wider than the screen. (I hope you understand what I'm going for.)

I'm just curious how I would go about implementing something like this? How can I force the text to stay on one line?

Answer Source

Here's a fairly simple way to do it. First, set up a div containing your long text:

<div id="container">
Here is the long content, long long content. So long. Too long.

You can use some css to automatically handle the truncation and ellipsis:

div#container {
    /* among other settings: see fiddle */
    width: 200px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;

If you then determine the native, untruncated width of the content, you can use jQuery's .animate() to move that content at a consistent speed -- even if you don't know the length of the text until runtime (as would be the case with a twitter feed). Here's a somewhat mechanical way of getting the measurement:

var true_width = ( function(){
  var $tempobj = $('#container') // starting with truncated text div container
      .clone().contents() // duplicate the text
      .wrap('<div id="content"/>') // wrap it in a container
      .parent().appendTo('body') // add this to the dom
      .css('left','-1000px'); // but put it far off-screen
  var result = $tempobj.width(); // measure it
  $tempobj.remove(); // clean up
  return result;

Finally, some animation:

$('#container').one('mouseenter', function(){ // perhaps trigger once only
  var shift_distance = true_width - $(this).width(); // how far to move
  var time_normalized = parseInt(shift_distance / 100, 10) * 1000; // speed
  $(this).contents().wrap('<div id="content">').parent() // wrap in div
        left: -shift_distance,
        right: 0
    }, time_normalized, 'linear'); // and move the div within its "viewport"

Regardless of the length of the text, you'll get a consistent speed of about one second per 100 pixels (adjust as desired). Resetting or rewinding content on mouseleave is left as an exercise. This approach has some naïve bits, but may give you some ideas.

Here's a working example:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download