2011年8月31日 星期三

[JavaScript] How to auto truncate text?

Sometimes we need to auto truncate text when the width of text division is not enough to fit the text. For example, we have a text like "Hello, I am a long long long text." But the text division only can show "Hello, I am a long long". I this case, the last long could not be shown normal. To ensure text presentation normally in screen, we need a function to calculate the width of input text and auto truncate text with tail token (ex: ...).

JavaScript code:
function autoEllipseText(element, text, width)
{
   element.innerHTML = '' + text + '';
   inSpan = document.getElementById('ellipsisSpan');
   if(inSpan.offsetWidth > width)
   {
      var i = 1;
      inSpan.innerHTML = '';
      while(inSpan.offsetWidth < (width) && i < text.length)
      {
         inSpan.innerHTML = text.substr(0,i) + '...';
         i++; 
      } 
                
      returnText = inSpan.innerHTML; 
      element.innerHTML = '';
      return returnText;
   }
   return text;
}

Usage:
function setCellText()
{
   cellElement = document.getElementById('textCell');
   textBoxElement = document.getElementById('cellText');
   cellElement.innerHTML = 
       autoEllipseText(cellElement, textBoxElement.value, 80);
}

References:

沒有留言:

張貼留言