Wolfgang Adamec
Wolfgang Adamec

Reputation: 8544

JavaScript/jQuery determine the length of a text "in advance"

I'm developing a web app with jQuery. I have a table with fixed-width columns, and javascript populated row contents.

Problem: One column has a width of 140px. Most of the sentences in this column are short and fit into this width. The font is NOT monospaced. There are a few long sentences, and there the td's have 2 lines and the height of the row becomes greater than 20px.

I do not want this to happen, so I have to shorten the long sentences

My first idea was to fill the td with the value and shortly after that to check the height of the td or row. And when the height is larger then 20px I have to shorten the sentence.

But I think this would cause the table rows to "flicker" when the rows get the values.

So the other idea is to make a invisible div or span and to do the same thing described as before.

Is there somebody who did this before and found a good solution for my problem?

Upvotes: 0

Views: 152

Answers (3)

aaron-bond
aaron-bond

Reputation: 3349

What about setting the height of the cell and then using text-overflow: ellipsis?

table td { text-overflow: ellipsis; max-height: 20px; }

EDIT: fixed the fiddle - Here's an example: JSFiddle - td and ellipsis

Upvotes: 1

Magnus
Magnus

Reputation: 980

There's no way to calculate what the size of the text will be - or at least there's no portable way. You won't even be able to know for sure which font will be used.

What you might do instead is use CSS to force the td to a fixed size and ignore all overflowing text. overflow: hidden should get you going. Might also want to use white-space: nowrap as well.

Upvotes: 2

James Donnelly
James Donnelly

Reputation: 128836

You could just prevent the resizing with CSS:

table { table-layout:fixed; }
table td, table th { white-space:nowrap; overflow:none; }

Upvotes: 1

Related Questions