0

I have an array of items that is to be displayed inside a box of width 500px. Suppose the array is [john, johnbbab, johnabraham] and I need to display either the complete string or give ellipses accordingly if the text overflow. eg: If the box cannot hold the second item i.e johnbbab, the contents of the box will look like [john, ...].

The issue I'm facing is to determine how to render this depending on the width of the text assuming the fontsize is 10px.

PS: Need this to be done is Javascript

johnbbab
  • 113
  • 2
  • 4
  • 9
  • 1
    What have you tried so far? – otejiri Oct 20 '21 at 07:57
  • 1
    I am looping through the array checking if the length currently exceeds 500/10 px considering the font size of the text and adds strings to a result variable . If yes then I discard the loop and prints the result. – johnbbab Oct 20 '21 at 08:01
  • what about css? text-overflow: ellipsis; nevermind. I just noticed your PS – Dov Rine Oct 20 '21 at 08:05
  • Got it. Wrote a function that can calculate the width of text and used a loop to iterate over the array checking if the width exceeds. Check this link for reference: https://stackoverflow.com/questions/58704990/calculate-pixel-width-of-text-without-knowing-font-in-react-javascript – johnbbab Oct 20 '21 at 08:34

2 Answers2

0

Hum, can't you just put thos name in with a class ? With that, you can loop over all and calc the sum of width of them. You can check if the sum if highter or lower than the parent and make your change if needed.

No need to know the font-size or box's width with that.

Nalar
  • 1
0

You can use flexbox and set the div content based on the width of the div. You can try tailoring this to suite your needs

// short width 190px
// const list = ["john", "johnbbab", "johnabraham"];

// long width 491
const list = ["john", "johnbbab", "johnabraham", "peterparker","johnsnow","josemourinho","olegunnar"]; 


// if width is short
document.getElementById("names").innerHTML = list;

// you can set maybe 190px as width to shrink the names
if (document.getElementById("names").offsetWidth > 190) {

document.getElementById("names").innerHTML = `${list[0]}...`;

}
#names {
width: fit-content;
background-color: green;
padding: 5px;
color: white;
}
<div id="names" ></div>
otejiri
  • 1,017
  • 6
  • 20