ChatGPT解决这个技术问题 Extra ChatGPT

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

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

Bear in mind that text-overflow:ellipsis; doesn't work at all in Firefox -- see this question for more: stackoverflow.com/questions/4927257/…
I just had to do something similar. Checking whether element.offsetWidth < element.scrollWidth as per this answer seems to work so far.
Note for posterity: text-overflow:ellipsis; now works in Firefox; it was added in Firefox 7 (released September 2011).

B
Bob

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());
    }
});

Thanks, works like a charm! However if you want to make it more efficient you might consider replacing bind() with on() like so: $(document).on('mouseenter', '.mightOverflow', function() { ... });
If you want the tooltip automatically removed if the text is no longer overflowing modify to: $(document).on('mouseenter', '.mightOverflow', function() { var $t = $(this); var title = $t.attr('title'); if (!title){ if (this.offsetWidth < this.scrollWidth) $t.attr('title', $t.text()) } else { if (this.offsetWidth >= this.scrollWidth && title == $t.text()) $t.removeAttr('title') } });
mouseenter is the event we bind to or listen for. We don't actually have to add the tooltip to the elements until someone actually mouses over them. So we defer the addition until that point of mouseenter on any one of the DOM elements with the class "mightoverflow". Just-In-Time-Tooltips
"As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document" for more info see api.jquery.com/bind and api.jquery.com/on
It doesn't work on IE10 - offsetWidth is identical to scrollWidth, both giving me the truncated width.
S
Snæbjørn

Here's a pure CSS solution. No need for jQuery. It won't show a tooltip, instead it'll just expand the content to its full length on mouseover.

Works great if you have content that gets replaced. Then you don't have to run a jQuery function every time.

.might-overflow {
    text-overflow: ellipsis;
    overflow : hidden;
    white-space: nowrap;
}

.might-overflow:hover {
    text-overflow: clip;
    white-space: normal;
    word-break: break-all;
}

It's not as good as tooltip, because it may break the layout.
The problem with tooltips is they don't work on mobile, at least for now. This answer could (read: probably will) break the layout, but it could be adapted to, for example, have a different background color for the hovered element. This still wouldn't work on mobile, but it is another option for desktop.
Thanks for this great answer which perfectly covers my needs. Using some JavaScript, we could imagine making the block absolutely positionned so that it doesn't break the layout.
It's a nice answer, better than bloating javascript on a css issue. Clearly ellipsis SHOULD have an automated title option, the way it's implemented at the moment is lacking sense. Too bad css doesnt allow to only :hover if the last characters are '...'
when there is horizontal scroller on page, tooltip content is displaying on different place of page not near the hover element. any suggestion on it?
H
Hannes

Here are two other pure CSS solutions:

Show the truncated text in place:

.overflow { overflow: hidden; -ms-text-overflow: ellipsis; text-overflow: ellipsis; white-space: nowrap; } .overflow:hover { overflow: visible; } .overflow:hover span { position: relative; background-color: white; box-shadow: 0 0 4px 0 black; border-radius: 1px; }

Long text that might overflow. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ad recusandae perspiciatis accusantium quas aut explicabo ab. Doloremque quam eos, alias dolore, iusto pariatur earum, ullam, quidem dolores deleniti perspiciatis omnis.

Show an arbitrary "tooltip":

.wrap { position: relative; } .overflow { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; pointer-events:none; } .overflow:after { content:""; display: block; position: absolute; top: 0; right: 0; width: 20px; height: 15px; z-index: 1; border: 1px solid red; /* for visualization only */ pointer-events:initial; } .overflow:hover:after{ cursor: pointer; } .tooltip { /* visibility: hidden; */ display: none; position: absolute; top: 10; left: 0; background-color: #fff; padding: 10px; -webkit-box-shadow: 0 0 50px 0 rgba(0,0,0,0.3); opacity: 0; transition: opacity 0.5s ease; } .overflow:hover + .tooltip { /*visibility: visible; */ display: initial; transition: opacity 0.5s ease; opacity: 1; }

Long text that might overflow Long text that might overflow. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ad recusandae perspiciatis accusantium quas aut explicabo ab. Doloremque quam eos, alias dolore, iusto pariatur earum, ullam, quidem dolores deleniti perspiciatis omnis.


This is exactly what I was looking for!
Excellent solution, exactly what I need. Thank you !
E
Elezar

uosɐſ's answer is fundamentally correct, but you probably don't want to do it in the mouseenter event. That's going to cause it to do the calculation to determine if it's needed, each time you mouse over the element. Unless the size of the element is changing, there's no reason to do that.

It would be better to just call this code immediately after the element is added to the DOM:

var $ele = $('#mightOverflow');
var ele = $ele.eq(0);
if (ele.offsetWidth < ele.scrollWidth)
    $ele.attr('title', $ele.text());

Or, if you don't know when exactly it's added, then call that code after the page is finished loading.

if you have more than a single element that you need to do this with, then you can give them all the same class (such as "mightOverflow"), and use this code to update them all:

$('.mightOverflow').each(function() {
    var $ele = $(this);
    if (this.offsetWidth < this.scrollWidth)
        $ele.attr('title', $ele.text());
});

+1, doing it on page load seems simpler but also provides more possibilities. ie. you may want to style this element that has a tooltip with an dotted underline to "signal" the tooltip. such as $(".mightOverflow").each(function() { if( $(this).offsetWidth < $(this).scrollWidth && !$(this).attr('title')){ $(this).attr('title', $(this).text()); $(this).css('border-bottom', '1px dotted #A8A8A8'); } });
'each time you mouse over' is wrong (now at least - I don't know if the answer was updated) It does check if it was previously calculated '&& !$this.attr('title')'
No, that just keeps it from adding the title attribute again. The calculation to determine if it's needed is still done. this.offsetWidth < this.scrollWidth and possibly even the check for !$this.attr('title') will be performed each time you mouse over the element.
The issue with this method is that all the elements are checked at once (potential performance impact) and it only calculates once, so that if the user shrinks the browser causing things to get truncated or expands, causing them to no longer be truncated you cannot update the presence of a tooltip. Attaching your code to window resize again would have a performance issue as every item checks its size. By using event delegation "$(document).on('mouseenter', '.mightOverflow', ..." and delaying the check till you mouseover the element, you can update on the fly and only check 1 element @ a time
It doesn't work on IE10 - offsetWidth is identical to scrollWidth, both giving me the truncated width.
T
Tony Brix

Here is my jQuery plugin:

(function($) {
    'use strict';
    $.fn.tooltipOnOverflow = function() {
        $(this).on("mouseenter", function() {
            if (this.offsetWidth < this.scrollWidth) {
                $(this).attr('title', $(this).text());
            } else {
                $(this).removeAttr("title");
            }
        });
    };
})(jQuery);

Usage:

$("td, th").tooltipOnOverflow();

Edit:

I have made a gist for this plugin. https://gist.github.com/UziTech/d45102cdffb1039d4415


It doesn't work on IE10 - offsetWidth is identical to scrollWidth, both giving me the truncated width.
@SsjCosty why are you testing on IE 10? There should be no one using IE 10 at this point, since anyone who can install IE 10 can install IE 11.
Ah well we have a company policy that our minimum IE version supported is 10. Also because a lot of our clients (some banks and various institutions) still use IE10. Oh well.
@SsjCosty Yes, this is the problem in big companies. There is no money for the IT to get rid of 5 years old and incompatible browser. But don't worry, the management receives lot of bonus... :-)) A little off topic, I know.
R
Rahi.Shah

We need to detect whether ellipsis is really applied, then to show a tooltip to reveal full text. It is not enough by only comparing "this.offsetWidth < this.scrollWidth" when the element nearly holding its content but only lacking one or two more pixels in width, especially for the text of full-width Chinese/Japanese/Korean characters.

Here is an example: http://jsfiddle.net/28r5D/5/

I found a way to improve ellipsis detection:

Compare "this.offsetWidth < this.scrollWidth" first, continue step #2 if failed. Switch css style temporally to {'overflow': 'visible', 'white-space': 'normal', 'word-break': 'break-all'}. Let browser do relayout. If word-wrap happening, the element will expands its height which also means ellipsis is required. Restore css style.

Here is my improvement: http://jsfiddle.net/28r5D/6/


S
Steven

I created a jQuery plugin that uses Bootstrap's tooltip instead of the browser's build-in tooltip. Please note that this has not been tested with older browser.

JSFiddle: https://jsfiddle.net/0bhsoavy/4/

$.fn.tooltipOnOverflow = function(options) {
    $(this).on("mouseenter", function() {
    if (this.offsetWidth < this.scrollWidth) {
        options = options || { placement: "auto"}
        options.title = $(this).text();
      $(this).tooltip(options);
      $(this).tooltip("show");
    } else {
      if ($(this).data("bs.tooltip")) {
        $tooltip.tooltip("hide");
        $tooltip.removeData("bs.tooltip");
      }
    }
  });
};

S
Sebastian

Here's a Vanilla JavaScript solution:

var cells = document.getElementsByClassName("cell"); for(const cell of cells) { cell.addEventListener('mouseenter', setTitleIfNecessary, false); } function setTitleIfNecessary() { if(this.offsetWidth < this.scrollWidth) { this.setAttribute('title', this.innerHTML); } } .cell { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; border: 1px; border-style: solid; width: 120px; }

hello world!
hello mars! kind regards, world


Note that this solution only works on static websites which load content immediately (otherwise the code must be re-run multiple times), and only works if the window/container size does not decrease. If a text doesn't truncate when the page is loaded, but the container is resized so it has to truncate - this will not re-add the tooltip. Still - an elegant and simple solution! +1
F
FarukT

This was my solution, works as a charm!

    $(document).on('mouseover', 'input, span', function() {
      var needEllipsis = $(this).css('text-overflow') && (this.offsetWidth < this.scrollWidth);
      var hasNotTitleAttr = typeof $(this).attr('title') === 'undefined';
      if (needEllipsis === true) {
          if(hasNotTitleAttr === true){
            $(this).attr('title', $(this).val());
          }
      }
      if(needEllipsis === false && hasNotTitleAttr == false){
        $(this).removeAttr('title');
      }
  });

Hi @FarukT your solution is working fine for me, thankyou so much. I want to ask if I have two html tags suppose input & span and I want to calculate the offsetWidth of both these tags at the same to do some Arithmetic calculations using those offsetWidth. How would I do that?
Hi @KunalTyagi, you can to it with 2 separated functions, I was writed only one with input and span but you can replicate this function 2 time, forexample first function with only input and in second function only span. like this: $(document).on('mouseover', 'input', function() {...}); and second one $(document).on('mouseover', 'span', function() {...});
M
Mark Costello

If you want to do this solely using javascript, I would do the following. Give the span an id attribute (so that it can easily be retrieved from the DOM) and place all the content in an attribute named 'content':

<span id='myDataId' style='text-overflow: ellipsis; overflow : hidden;
 white-space: nowrap; width: 71;' content='{$myData}'>${myData}</span>

Then, in your javascript, you can do the following after the element has been inserted into the DOM.

var elemInnerText, elemContent;
elemInnerText = document.getElementById("myDataId").innerText;
elemContent = document.getElementById("myDataId").getAttribute('content')
if(elemInnerText.length <= elemContent.length)
{
   document.getElementById("myDataId").setAttribute('title', elemContent); 
}

Of course, if you're using javascript to insert the span into the DOM, you could just keep the content in a variable before inserting it. This way you don't need a content attribute on the span.

There are more elegant solutions than this if you want to use jQuery.


Nice. Since I am using JQuery in other part of this page - what is the JQuery elegant solution??
$("#myDataId").attr("title", function() { var innerText = $(this).text(); var content = $(this).attr("content"); if (innerText.length <= content.length) { return content; } return null; });
I tried your first suggestion with pure javascript - it doesn't work. the 'innerText' property save the complete length of the text even if it not show completely on screen so always: elemInnerText.length == elemContent.length !!
The style of your span is width 71. Why not check if the width of the string is longer than that? If you wanted to do something really funky, you could add a hidden element without the text-overflow:ellipsis set and compare the widths of both. If the hidden one is wider than the non-hidden one, add a title attribute to the visible one.
f
fanfavorite

This is what I did. Most tooltip scripts require you to execute a function that stores the tooltips. This is a jQuery example:

$.when($('*').filter(function() {
   return $(this).css('text-overflow') == 'ellipsis';
}).each(function() {
   if (this.offsetWidth < this.scrollWidth && !$(this).attr('title')) {
      $(this).attr('title', $(this).text());
   }
})).done(function(){ 
   setupTooltip();
});

If you didn't want to check for ellipsis css, you could simplify like:

$.when($('*').filter(function() {
   return (this.offsetWidth < this.scrollWidth && !$(this).attr('title'));
}).each(function() {
   $(this).attr('title', $(this).text());
})).done(function(){ 
   setupTooltip();
});

I have the "when" around it, so that the "setupTooltip" function doesn't execute until all titles have been updated. Replace the "setupTooltip", with your tooltip function and the * with the elements you want to check. * will go through them all if you leave it.

If you simply want to just update the title attributes with the browsers tooltip, you can simplify like:

$('*').filter(function() {
   return $(this).css('text-overflow') == 'ellipsis';
}).each(function() {
   if (this.offsetWidth < this.scrollWidth && !$(this).attr('title')) {
      $(this).attr('title', $(this).text());
   }
});

Or without check for ellipsis:

$.when($('*').filter(function() {
   return (this.offsetWidth < this.scrollWidth && !$(this).attr('title'));
}).each(function() {
   $(this).attr('title', $(this).text());
});

Why the downvote? Please comment if you are doing that so people know what the problem is. Thanks.
M
Miguel Sánchez Villafán

This is what I ended up doing based on https://stackoverflow.com/a/13259660/1714951 and adding the removal of the title attribute when the element doesn't overflow anymore. This is pure JS (ES6), uses event delegation for performance (when using several elements with the same class) and guard clauses for readability:

// You may want to change document by an element closer to your target
// so that the handler is not executed as much
document.addEventListener( 'mouseenter', event => {
    let eventTarget = event.target;
    // This could be easily applied to text-truncate instead of my-class if you use bootstrap
    if ( !eventTarget.classList?.contains( 'my-class' ) ) {
        return;
    }
    if ( eventTarget.offsetWidth < eventTarget.scrollWidth ) {
        eventTarget.setAttribute( 'title', eventTarget.innerText );
        return;
    }
    eventTarget.removeAttribute( 'title' );
}, true );

A
Alexander

I have CSS class, which determines where to put ellipsis. Based on that, I do the following (element set could be different, i write those, where ellipsis is used, of course it could be a separate class selector):

$(document).on('mouseover', 'input, td, th', function() {
    if ($(this).css('text-overflow') && typeof $(this).attr('title') === 'undefined') {
        $(this).attr('title', $(this).val());
    }
});

i my case this was an anchor so I used this.text() instead of val()
B
Brian Gabriel

None of the solutions above worked for me, but I figured out a great solution. The biggest mistake people are making is having all the 3 CSS properties declared on the element upon pageload. You have to add those styles+tooltip dynamically IF and ONLY IF the span you want an ellipses on is wider than its parent.

    $('table').each(function(){
        var content = $(this).find('span').text();
        var span = $(this).find('span');
        var td = $(this).find('td');
        var styles = {
            'text-overflow':'ellipsis',
            'white-space':'nowrap',
            'overflow':'hidden',
            'display':'block',
            'width': 'auto'
        };
        if (span.width() > td.width()){
            span.css(styles)
                .tooltip({
                trigger: 'hover',
                html: true,
                title: content,
                placement: 'bottom'
            });
        }
    });

D
Dexygen

You could possibly surround the span with another span, then simply test if the width of the original/inner span is greater than that of the new/outer span. Note that I say possibly -- it is roughly based on my situation where I had a span inside of a td so I don't actually know that if it will work with a span inside of a span.

Here though is my code for others who may find themselves in a position similar to mine; I'm copying/pasting it without modification even though it is in an Angular context, I don't think that detracts from the readability and the essential concept. I coded it as a service method because I needed to apply it in more than one place. The selector I've been passing in has been a class selector that will match multiple instances.

CaseService.applyTooltip = function(selector) {
    angular.element(selector).on('mouseenter', function(){
        var td = $(this)
        var span = td.find('span');

        if (!span.attr('tooltip-computed')) {
            //compute just once
            span.attr('tooltip-computed','1');

            if (span.width() > td.width()){
                span.attr('data-toggle','tooltip');
                span.attr('data-placement','right');
                span.attr('title', span.html());
            }
        }
    });
}