Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show content in title when text-overflow

Tags:

html

jquery

css

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?

like image 951
JD Isaacks Avatar asked Sep 03 '10 20:09

JD Isaacks


1 Answers

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() {
  var $this = $(this);
  if ($this.width() > max_width) {
    $this.attr("title", $this.text());
  }
});

See: http://jsbin.com/alepa3

like image 154
Richard M Avatar answered Sep 22 '22 14:09

Richard M