JavaScript: Truncating text based on dimensions of an external object

I want to use JavaScript to slice this text so that it matches the object the text is in and add "..." at the end.

For example: JavaScript received data from a third-party web service and should put the text in a 200 x 300 px div. The length of the text varies, so let's say it takes up a lot more space than intended.

How to determine at what point the text will break through the border and prevent this by chopping the text and adding "..." at the end?

+4
source share
4 answers

There are several jQuery plugins that can do this.

+4
source

If you don't mind using the canvas element, you can use it to measure the width of the text. Here is an example:

http://uupaa-js-spinoff.googlecode.com/svn/trunk/uupaa-excanvas.js/demo/8_2_canvas_measureText.html

+1
source

ruzee.com has a solution that uses prototype.js and a small bit of code [MIT licensed] to do what you want; demo

+1
source

You can also view the CSS 3 text-overflow property, which also does this.

http://www.w3.org/TR/2001/WD-css3-text-20010517/#text-overflow-props

You can check if the browser supports it, so you can always add JavaScript back.

 if (!'textOverflow' in document.createElement('div').style) { // Use JavaScript solution here } 
+1
source

All Articles