views:

49

answers:

1

hey I'm looking for a good way to ellipsify text in a yui datatable. By that I mean, formatting the text so that it fits nicely into its cell and has an ellipse (...) trailing it if the text had to be truncated.

I want to do this wihtout the use of CSS selectors, because I have a large dataset and selecting each cell by classname would be expensive.

Any good suggestions on how to do this using a formatter or something similar.

+1  A: 

I came up with this idea. The script will measure the content of div and if its width is above div's width, it will shrink the content a little bit, so ellipsis char could fit, and put ellipsis char:

<style>
div {
    width: 100px;
    height: 1em;
    overflow: hidden;
    white-space: nowrap;
}
</style>
<div>Short text.</div>
<div>Extremely long text.</div>
<script>
(function () {
    var list = document.getElementsByTagName('div');
    for (var i = 0; i < list.length; i++) {
        var spanElement = document.createElement('span');
        while (list[i].childNodes.length)
            spanElement.appendChild(list[i].firstChild);
        list[i].appendChild(spanElement);
        if (list[i].firstChild.offsetWidth > list[i].offsetWidth) {
            var ellipsisSpanElement = document.createElement('span');
            ellipsisSpanElement.appendChild(document.createTextNode('…'));
            list[i].appendChild(ellipsisSpanElement);
            var newWidth = list[i].offsetWidth - ellipsisSpanElement.offsetWidth;
            list[i].firstChild.setAttribute('style',
                'overflow: hidden; white-space: nowrap; display: block; float: left; width: ' + newWidth + 'px');
        }
    }
})();
</script>

I didn't use YUI in this example, I hardly know this library. I'm sure this code could be written much simpler by avoiding all of these DOM methods and using YUI's substitutes.

Disadvantage: the script roughly cuts a letter at the end, which looks not so nice. But measuring width of the content letter by letter, or even in logarithmic manner, costs too much time. For now this is my best idea.

Solution: Use text-overflow: ellipsis in browsers that support this and script in others.

List of all variants of text-overflow: ellipsis, many of these are not working yet. Tested with success in IE 8.0, Opera, Chrome.

text-overflow: ellipsis;
-o-text-overflow: ellipsis;
-icab-text-overflow: ellipsis;
-khtml-text-overflow: ellipsis;
-moz-text-overflow: ellipsis;
-webkit-text-overflow: ellipsis;
pepkin88