Why not do it entirely in CSS?
This can be done using CSS and avoid any client side processing. If you would like to speed up table rendering you can also set table's table-layout
to fixed which will prevent table cells from recalculating dimensions based on content. It renders tables (especially long ones) much much faster if you can guarantee that your content will actually fit.
Anyway. Here's some CSS:
table
{
table-layout: fixed;
}
td
{
width: 50px; /* set this to whatever width you'd like */
overflow: hidden;
text-overflow: ellipsis; /* IE, Safari, Chrome */
-o-text-overflow: ellipsis; /* this one's for Opera */
white-space: nowrap;
}
This will display correctly in IE, Chrome, Opera and Safari. But FF won't display it. But there's a workaround for it as well. There's information about if on Mozilla's web site. It says -moz-binding
can be used to serve this purpose. And this blog post shows you how to do it.
Javascript approach
But if you'd like to take the script approach I suggest you don't break the word after a certain amount of characters, because you'll end up with various length words depending on letter used in them. "WMWMWM" is much longer than "IIIIII" even though they are both 6 characters long.
The best way would be to do it this way:
- create a dummy absolutely positioned and hidden (by visibility and not display)
div
but keep it's font styles completely the same as your table cells have.
- loop through all cells and for each:
- take a cell
- copy cell content into
div
- check
div
width fits appropriate width and if it does copy its content back to cell and go back to step 1
- remove last character and attach an ellipsis
- go to step 3
This way you'll end up with the longest possible strings in cells that fit cell width. So if some word has letters that are wide (like m, w) or letters that are very narrow (i), it will clip the string correctly and only when it needs to.