HTML - how can I show tooltip ONLY when ellipsis is activated
Solution 1
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());
}
});
Solution 2
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;
}
Solution 3
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;
}
<div>
<span class="overflow" style="float: left; width: 50px">
<span>Long text that might overflow.</span>
</span>
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.
</div>
.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;
}
<div>
<span class="wrap">
<span class="overflow" style="float: left; width: 50px">Long text that might overflow</span>
<span class='tooltip'>Long text that might overflow.</span>
</span>
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.
</div>
Solution 4
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());
});
Solution 5
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
Related videos on Youtube
Comments
-
Spiderman over 2 years
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 whenellipsis
is activated?*Browser: Internet Explorer
-
Spudley about 13 yearsBear in mind that
text-overflow:ellipsis;
doesn't work at all in Firefox -- see this question for more: stackoverflow.com/questions/4927257/… -
Martin Smith about 12 yearsI just had to do something similar. Checking whether
element.offsetWidth < element.scrollWidth
as per this answer seems to work so far. -
Adrien Be almost 10 yearsellipsis detection: stackoverflow.com/questions/7738117/…
-
sleske about 8 yearsNote for posterity:
text-overflow:ellipsis;
now works in Firefox; it was added in Firefox 7 (released September 2011).
-
-
Spiderman about 13 yearsNice. Since I am using JQuery in other part of this page - what is the JQuery elegant solution??
-
Mark Costello about 13 years
$("#myDataId").attr("title", function() { var innerText = $(this).text(); var content = $(this).attr("content"); if (innerText.length <= content.length) { return content; } return null; });
-
Spiderman about 13 yearsI 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 !!
-
Mark Costello about 13 yearsThe 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.
-
Ziad over 11 yearsThanks, 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() { ... });
-
Chris Janssen about 11 yearsIf 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') } });
-
Kevin Meredith almost 11 yearsCould someone please post a jsfiddle for this solution? I don't fully understand the "mouseenter" part.
-
Jason Kleban almost 11 yearsmouseenter 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
-
Adrien Be almost 10 years
"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 -
Adrien Be almost 10 years+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'); } });
-
Rune Jeppesen over 9 years'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')'
-
Elezar over 9 yearsNo, 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. -
chris about 9 yearsIs this solution correct? offsetWidth takes the border into account, so if the border is the same size as the overflow this suggestion will not work. (It was surfaced as an edge case for us) clientWidth seems like it would be a better option.
-
Jason Kleban about 9 yearssurely this code will need adjustment in some scenarios and be fundamentally inappropriate for others.
-
Chris Janssen about 9 yearsThe 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
-
Alexander over 8 yearsIt's not as good as tooltip, because it may break the layout.
-
Linh Dam over 8 yearsIf you need to understand offsetWidth, scrollWidth, and clientWidth, here is a very good explanation: stackoverflow.com/a/21064102/1815779
-
trysis almost 8 yearsThe 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.
-
fanfavorite over 7 yearsWhy the downvote? Please comment if you are doing that so people know what the problem is. Thanks.
-
SsjCosty over 7 yearsIt doesn't work on IE10 - offsetWidth is identical to scrollWidth, both giving me the truncated width.
-
SsjCosty over 7 yearsIt doesn't work on IE10 - offsetWidth is identical to scrollWidth, both giving me the truncated width.
-
SsjCosty over 7 yearsIt doesn't work on IE10 - offsetWidth is identical to scrollWidth, both giving me the truncated width.
-
Jason Kleban over 7 yearsperhaps, but verify that it /is/ working for you in other browsers, or you might not be putting the behavior on the right element? Or is there a IE10-unsupported feature in use nearby that might be interfering?
-
Tony Brix over 7 years@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.
-
Elezar over 7 years@SsjCosty, I've deleted my VM that had IE10 since Microsoft no longer supports it, so I can't test this currently. However, I use scrollWidth in quite a few places, and they were all tested in IE10 when it was supported. It's possible you've found some bug in IE10, but I think it's more likely that something else is going on with your code. For example, if you have nested elements, it's easy to look at the wrong element when trying to determine dimensions.
-
SsjCosty over 7 yearsIt could be, though the same code works in IE11, Chrome and FF. I've found a workaround since then though, so it's fine.
-
SsjCosty over 7 yearsAh 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.
-
sylbru about 7 yearsThanks 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.
-
Basheer AL-MOMANI about 7 yearsi my case
this
was ananchor
so I usedthis.text()
instead ofval()
-
Steven almost 7 yearsHere is the JSFiddle for this example: jsfiddle.net/rpsz1noe/1
-
John over 6 yearsIt'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 '...'
-
sms almost 6 yearsIn IE, the scrollwidth is 1px more than what it should be
-
Blue Smith almost 6 yearsThanks, this tip is really elegant :)
-
AshD over 5 yearsWe are using the multi-line ellipsis using the -webkit-line-clamp strategy. Will this offset width comparison work in that case? It does not work for me in the sense that the offset width and scroll width is the same even when the element shows ellipsis, so I thought I would check. Thank you.
-
Praneet Nadkar over 5 yearsThis is exactly what I was looking for!
-
Agu V about 5 yearsExcellent solution, exactly what I need. Thank you !
-
Kunal Tyagi almost 4 yearsHi @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?
-
FarukT almost 4 yearsHi @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() {...});
-
Peter VARGA over 3 years@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.
-
Sebastian almost 3 yearsNote 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
-
vishal-mote almost 3 yearswhen there is horizontal scroller on page, tooltip content is displaying on different place of page not near the hover element. any suggestion on it?
-
Shabbir Essaji about 2 yearsThis works on fiddle jsfiddle.net/swsessaji/cdw1ykrm/3
-
Shabbir Essaji about 2 yearsBut if I use Handsontable, this solution isn;t prefect