Tuesday, February 24, 2009

Truncate a string to fit within a given pixel width.


  1. function fitStringToWidth(str,width,className)
  2. {
  3. // str A string where html-entities are allowed but no tags.
  4. // width The maximum allowed width in pixels
  5. // className A CSS class name with the desired font-name and font-size. (optional)
  6. // ----
  7. // _escTag is a helper to escape 'less than' and 'greater than'
  8. function _escTag(s){ return s.replace("<","<").replace(">",">");}
  9. //Create a span element that will be used to get the width
  10. var span = document.createElement("span");
  11. //Allow a classname to be set to get the right font-size.
  12. if (className) span.className=className;
  13. span.style.display='inline';
  14. span.style.visibility = 'hidden';
  15. span.style.padding = '0px';
  16. document.body.appendChild(span);
  17. var result = _escTag(str); // default to the whole string
  18. span.innerHTML = result;
  19. // Check if the string will fit in the allowed width. NOTE: if the width
  20. // can't be determinated (offsetWidth==0) the whole string will be returned.
  21. if (span.offsetWidth > width) {
  22. var posStart = 0, posMid, posEnd = str.length, posLength;
  23. // Calculate (posEnd - posStart) integer division by 2 and
  24. // assign it to posLength. Repeat until posLength is zero.
  25. while (posLength = (posEnd - posStart) >> 1) {
  26. posMid = posStart + posLength;
  27. //Get the string from the begining up to posMid;
  28. span.innerHTML = _escTag(str.substring(0,posMid)) + '…';
  29. // Check if the current width is too wide (set new end)
  30. // or too narrow (set new start)
  31. if ( span.offsetWidth > width ) posEnd = posMid; else posStart=posMid;
  32. }
  33. result = '' +
  34. str.replace("\"",""") + '">' +
  35. _escTag(str.substring(0,posStart)) +
  36. '…<\/abbr>';
  37. }
  38. document.body.removeChild(span);
  39. return result;
  40. }

Refs:
Acronym

offsetWidth

No comments: