HTML - how can I show tooltip ONLY when ellipsis is activated

Spiderman picture Spiderman · Mar 29, 2011 · Viewed 151.5k times · Source

I have got a span with dynamic data in my page, with ellipsis style.

.my-class
{
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;  
  width: 71px;
}
<span id="myId" class="my-class"></span>
document.getElementById('myId').innerText = "...";

I'd like to add to this element tooltip with the same content, but I want it to appear only when the content is long and the ellipsis appear on screen.

Is there any way to do it?
Does the browser throw an event when ellipsis is activated?

*Browser: Internet Explorer

Answer

Jason Kleban picture Jason Kleban · Nov 6, 2012

Here's a way that does it using the built-in ellipsis setting, and adds the title attribute on-demand (with jQuery) building on Martin Smith's comment:

$('.mightOverflow').bind('mouseenter', function(){
    var $this = $(this);

    if(this.offsetWidth < this.scrollWidth && !$this.attr('title')){
        $this.attr('title', $this.text());
    }
});