I have a component where I am displaying a colon (:) separated list of text. I only need to display that part of the text up to the colon from the start which will be completely visible without over flowing. The rest needs to be truncated. I am using the following code to check for overflow.
function checkOverflow(el) {
var curOverflow = window.getComputedStyle(el).overflow
if (!curOverflow || curOverflow === 'visible') {
el.style.overflow = 'hidden'
}
var isOverflowing = el.clientWidth < el.scrollWidth
el.style.overflow = curOverflow
return isOverflowing
}
const tableComponent = () => {
const view = document.getElementById('outer-view')
console.log(checkOverflow(view))
console.log(view.scrollWidth, view.clientWidth)
}
document.addEventListener('readystatechange', () => {
if (document.readyState === 'complete') {
tableComponent()
}
})
#outer-view {
height: 100%;
width: 100%;
background-color: lightpink;
overflow: hidden;
}
<div id="outer-view">{status}</div>
- Here status is the variable containing the string of colon separated texts. (eg. XQV:HGAHGCDHD:KJDGKDGKDHGD.....).
- Also for more clarity lets assume that this div is inside another div whose max-width is set to 300px.
- The text will always be single line. It will never be multiline.
- It is not clamped with elipsis. I am not adding elipsis at the end if it overflows. I have a different logic to run and to change the ui if overflow occurs.
- I will need to detect overflow change on browser resize as well (which should not be a problem as I can call this function again on resize event.)
This code is based on this article but for every case whether the text overflows or not the checkOverflow() always returns false. I also tried checking the scrollWidth and the clientWidth but in every case their value is same. I also tried enclosing the string within a p tag and then try to get the width difference of the div and p tag but they are also the same in every case, irrespective of the fact whether the text overflows or not.
I have tried all the solutions mentioned but none of them seem to work. Any help in this matter will be greatly appreciated.
I know that there are multiple answers for my issue, but I wrote this article because none of the solutions seem to work in my case.
Thanks to @vsync for pointing out the missing details.