Home > Blockchain >  Wrong elipsis detection with scrollWidth when text length is close to width
Wrong elipsis detection with scrollWidth when text length is close to width

Time:03-16

I have to detect ellipsis on a span and so I found the method "e.offsetWidth < e.scrollWidth", it works well with short or long text, but I notice that when the text length is close to the container width, the ellipsis appears before that condition turn true.

Here is a JSfiddle showing the issue: https://jsfiddle.net/zgowrxbf/23/

Is there a better way to detect ellipsis ?

edit: the issue seems to be only on Firefox, but I have to support only this browser for my project

var offset = document.getElementById("test").offsetWidth;
var scroll = document.getElementById("test").scrollWidth;
var isEllipsis = offset < scroll;
console.log(offset   " "   scroll   " "   isEllipsis);
#test {
  display: block;
  width: 180px;
  border: 1px solid red;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  padding: 5px 10px;
  font-family: "Arial", sans-serif;
  font-size: 12px;
}
<span id="test">test xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx</span>

CodePudding user response:

I found this hacky solution https://stackoverflow.com/a/64689702/3703099

function isEllipsisActive(e) {
  var c = e.cloneNode(true);
  c.style.display = 'inline';
  c.style.width = 'auto';
  c.style.visibility = 'hidden';
  document.body.appendChild(c);
  const truncated = c.offsetWidth >= e.clientWidth;
  c.remove();
  return truncated;
}

I'm not a big fan as adding a new element to DOM everytime we do the check is an heavy cost for perf versus the previous method which just compare 2 attributes, but I couldn't find better :(, any better solution is still welcome

  • Related