views:

73

answers:

1

CSS3 introduces text-overflow so you can hide overflowing text and even add ellipses.

If the text is overflowing and hidden, I would like to show it as a tooltip when hovered.

The easiest way to do this is to add the text to the title attribute of the element. However that will make the text show whether it is overflowing or not.

I only want to show the tooltip when overflowed.

so if I had this:

<span>some text here</span>
<span>some more text here</span>

and it rendered like this:

some text here

some more...

The first one would have no tooltip since there is no need and the second would have a tooltip that showed:

some more text here

Is there any way to set this up?

+2  A: 

You can't do this with CSS alone, and I think any Javascript solution will depend on how your HTML is structured. However, if you have HTML structured like this:

<div id="foo">
  <span class="bar">Lorem ipsum dolor sit amet, consectetur.</span>
  <span class="bar">Lorem ipsum dolor sit amet, consectetur adipisicing elit.</span>
</div>

With the #foo element having your text-overflow declaration, and the bar class having a white-space: nowrap declaration. The you should be able to do something like this using jQuery:

var foo = $("#foo");
var max_width = foo.width();
foo.children().each(function() {
  if ($(this).width() > max_width) {
    $(this).attr("title", $(this).text());
  }
});

See: http://jsbin.com/alepa3

Richard M