Text Field Limit with Ellipse


/ Published in: ActionScript 3
Save to your folder(s)

This code sets the size of a text field and truncates the text to fit, adding an ellipse if necessary.


Copy this code and paste it in your HTML
  1. var myCopy:String = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras ullamcorper est in nibh. Integer dapibus, nisi at venenatis ullamcorper, metus eros vulputate nisi, in luctus erat sapien a mauris.\n\nSuspendisse dolor ipsum, congue at, commodo id, consectetur vel, dui. Donec vehicula egestas nibh. Aliquam imperdiet ligula a dolor. Praesent nec tortor id orci semper consectetur. Vivamus dictum lorem nec libero. Maecenas a pede. Aliquam felis nulla, adipiscing in, scelerisque et, rhoncus a, ipsum.\n\nPellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Maecenas rutrum augue at nulla. Vivamus egestas ornare sapien. Nunc lobortis. Aliquam auctor urna quis justo. Suspendisse elit orci, gravida eleifend, suscipit ac, porta ultrices, nibh. Morbi dignissim mauris varius magna.";
  2.  
  3. copy_txt.height = 150; // HEIGHT MUST BE SET BEFORE APPLYING TEXT TO TEXTFIELD.
  4. copy_txt.text = myCopy;
  5.  
  6. var lastLine:String = copy_txt.getLineText(copy_txt.bottomScrollV - 1);
  7. var visibleLength:uint = copy_txt.getLineOffset(copy_txt.bottomScrollV - 1);
  8.  
  9. // REMOVE TRAILING SPACES FROM LAST VISIBLE LINE OF TEXT
  10. while(lastLine.substr(-1, 1) == " ")
  11. {
  12. lastLine = lastLine.substr(0, lastLine.length - 1);
  13. }
  14.  
  15. var lastLineWords:Array = lastLine.split(" ");
  16.  
  17. /* IF LAST WORD DOES NOT HAVE A RETURN OR PERIOD AT
  18.   THE END, REPLACE LAST WORD WITH AN ELIPSE */
  19. var lastChar:String = lastLineWords[lastLineWords.length - 1].substr(-1, 1);
  20.  
  21. if (lastChar != "." && lastChar.charCodeAt(0) != 13 && lastChar.charCodeAt(0) != 10)
  22. {
  23. lastLineWords[lastLineWords.length - 1] = ". . .";
  24. }
  25.  
  26.  
  27. var myNewCopy:String = myCopy.substr(0, visibleLength) + lastLineWords.join(" ");
  28.  
  29. copy_txt.text = myNewCopy + " "; // SPACE ADDED AT END SO TEXT DOESN'T WRAP UNNECESARILLY.

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.