Home > Software design >  Display data from an array depending on box width
Display data from an array depending on box width

Time:10-21

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

CodePudding user response:

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.

CodePudding user response:

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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related