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

19

294

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

Kuykendall answered 29/3, 2011 at 15:18 Comment(4)
Bear in mind that text-overflow:ellipsis; doesn't work at all in Firefox -- see this question for more: #4927757Specular
I just had to do something similar. Checking whether element.offsetWidth < element.scrollWidth as per this answer seems to work so far.Thermosetting
ellipsis detection: #7738617Grethel
Note for posterity: text-overflow:ellipsis; now works in Firefox; it was added in Firefox 7 (released September 2011).Hinze
D
185

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());
    }
});
Displease answered 6/11, 2012 at 21:24 Comment(15)
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() { ... });Gassy
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') } });Siegler
Could someone please post a jsfiddle for this solution? I don't fully understand the "mouseenter" part.Ianiana
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-TooltipsDisplease
"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/onGrethel
Is 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.Reprobation
surely this code will need adjustment in some scenarios and be fundamentally inappropriate for others.Displease
If you need to understand offsetWidth, scrollWidth, and clientWidth, here is a very good explanation: https://mcmap.net/q/37884/-understanding-offsetwidth-clientwidth-scrollwidth-and-height-respectivelySophisticated
It doesn't work on IE10 - offsetWidth is identical to scrollWidth, both giving me the truncated width.Velamen
perhaps, 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?Displease
Here is the JSFiddle for this example: jsfiddle.net/rpsz1noe/1Leveret
In IE, the scrollwidth is 1px more than what it should beGereld
We 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.Concordance
This works on fiddle jsfiddle.net/swsessaji/cdw1ykrm/3Governess
But if I use Handsontable, this solution isn;t prefectGoverness
T
92

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;
}
Toxoplasmosis answered 29/10, 2015 at 19:11 Comment(5)
It's not as good as tooltip, because it may break the layout.Crotchety
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.Designate
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.Legman
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 '...'Nunley
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?Billings
S
69

Here are two other pure CSS solutions:

  1. 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>
  1. 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;
}
<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>
Sandrasandro answered 22/10, 2018 at 13:21 Comment(4)
This is exactly what I was looking for!Whitworth
Excellent solution, exactly what I need. Thank you !Conall
Incredible solution. Will definitely be snagging this for laterArmistead
this solution will have tooltip even if text was not truncated which does not satisfy original questionGrainger
L
33

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());
});
Lockup answered 10/12, 2012 at 20:47 Comment(7)
+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'); } });Grethel
'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')'Harveyharvie
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.Lockup
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 timeSiegler
It doesn't work on IE10 - offsetWidth is identical to scrollWidth, both giving me the truncated width.Velamen
@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.Lockup
It could be, though the same code works in IE11, Chrome and FF. I've found a workaround since then though, so it's fine.Velamen
A
18

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

Agamogenesis answered 14/7, 2014 at 16:15 Comment(5)
It doesn't work on IE10 - offsetWidth is identical to scrollWidth, both giving me the truncated width.Velamen
@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.Agamogenesis
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.Velamen
@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.Cymar
Screw dinosaurs -- let them die off. Implement functionality for up to date browsers. If you're asked to implement new feature for discontinued product (like IE 🤮), suggest changing a jobRima
S
14

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:

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

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

Sourdough answered 27/5, 2014 at 6:2 Comment(0)
D
13

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; 
}
<div class="cell">hello world!</div>
<div class="cell">hello mars! kind regards, world</div>
Daveen answered 11/6, 2019 at 9:18 Comment(1)
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! +1Photoflood
L
12

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");
      }
    }
  });
};
Leveret answered 13/7, 2017 at 18:17 Comment(0)
A
4

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');
      }
  });
Amersham answered 3/7, 2019 at 15:18 Comment(2)
Hi @Amersham 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?Sivie
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() {...});Amersham
R
4

This is what I ended up doing based on https://mcmap.net/q/37872/-html-how-can-i-show-tooltip-only-when-ellipsis-is-activated 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 );
Raulrausch answered 22/5, 2021 at 17:1 Comment(0)
T
3

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.

Terryterrye answered 29/3, 2011 at 15:41 Comment(4)
Nice. Since I am using JQuery in other part of this page - what is the JQuery elegant solution??Kuykendall
$("#myDataId").attr("title", function() { var innerText = $(this).text(); var content = $(this).attr("content"); if (innerText.length <= content.length) { return content; } return null; });Terryterrye
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 !!Kuykendall
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.Terryterrye
R
3

Adding simple one-off solution for year 2022, when you should not use jQuery, and should not try to support discontinued products (like IE 🤮):

document.querySelectorAll('.overflow').forEach(span => {
  if (span.scrollWidth > span.clientWidth) {
    span.title = span.innerText
  }
})

Try it out: https://jsfiddle.net/metalim/cxw26smg/

Rima answered 15/10, 2022 at 7:1 Comment(0)
O
2

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());
});
Ordzhonikidze answered 30/5, 2013 at 19:56 Comment(1)
Why the downvote? Please comment if you are doing that so people know what the problem is. Thanks.Ordzhonikidze
C
1

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());
    }
});
Crotchety answered 20/11, 2015 at 16:48 Comment(1)
i my case this was an anchor so I used this.text() instead of val()Vibrate
M
0

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'
            });
        }
    });
Mute answered 15/11, 2013 at 0:0 Comment(0)
Z
0

In my case i used not only text-overflow: ellipsis; but also line-clamp property, so the ellipsis was applied only after the second line of text. Here is the styles of my div:

.text {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  text-overflow: ellipsis;
}

I'm using React here, but i think that approach can be applied to vanilla js too. Here it is:

const MyComponent = ({text}: {text: string}) => {
  const [titleActive, setTitleActive] = useState(false)
  const ref = useCallback<(node: HTMLDivElement) => void>(
    (node) => {
      if (node) {
        const blockWidth = node.offsetWidth

        /* setting width to `max-content` makes div's width equal to text 
           rendered in one line */
        node.style.width = 'max-content';
        const textWidth = node.offsetWidth;
        node.style.width = 'auto';
        
        /* the multiplier of `blockWidth` is the number of lines shown 
           before ellipsis applied. In my case this is 2 (same 
           as in `-webkit-line-clamp` css property).
           For one condition will be just `(textWidth > blockWidth)`
        */
        if (textWidth > blockWidth * 2) {
          setTitleActive(true)
        }
      }
    },
    []
  );

  return (
    <div 
      className="text" 
      title={titleActive ? text : undefined}
      ref={ref}
    >
      {text}
    </div>
  )
}
Zeitgeist answered 11/5, 2023 at 10:24 Comment(0)
G
0

Reusable solution for React

// useTitleWhenTruncated.ts

import { HTMLAttributes, useState } from 'react';

type TitleProps = Pick<HTMLAttributes<HTMLElement>, 'title' | 'onMouseEnter'>;

export function useTitleWhenTruncated(title: string): TitleProps {
  const [isTruncated, setIsTruncated] = useState(false);

  return {
    title: isTruncated ? title : undefined,
    onMouseEnter: event => {
      setIsTruncated(
        event.currentTarget.offsetWidth < event.currentTarget.scrollWidth,
      );
    },
  };
}


// usage example

const SampleComponent = ({ label }: { label: string }) => {
  const titleProps = useTitleWhenTruncated(label);
  
  return (
    <div 
      style={{ whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }} 
      {...titleProps}
    >
      {label}
    </div>
  );
}
Grainger answered 26/7, 2023 at 19:49 Comment(0)
A
0

for react, you can use title as attribute, instead of a third-party tooltip, in my case i use @mui/material Tooltip component

import { FC, HTMLAttributes, useRef } from 'react'
import { Tooltip } from '@mui/material'

export const AutoTooltip: FC<HTMLAttributes<HTMLSpanElement>> = ({ onMouseEnter, ...props }) => {
  const ref = useRef<string | null>(null)

  return (
    <Tooltip title={ref.current}>
      <span
        onMouseEnter={({ currentTarget }) => {
          if (currentTarget.scrollWidth > currentTarget.clientWidth) {
            ref.current = currentTarget.innerText
          }
        }}
        {...props}
      />
    </Tooltip>
  )
}

add ellipsis class if need:

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

use

<AutoTooltip className="truncate">
    {el.defaultParams.name}
</AutoTooltip>
Aquamarine answered 22/2 at 11:14 Comment(0)
U
-1

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());
            }
        }
    });
}
Underplay answered 7/1, 2016 at 16:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.