Paul
Paul

Reputation: 1966

JavaScript: Truncating text based on outer object's dimensions

I want to, using JavaScript, chop the given text to fit the object in which the text resides and add "..." at the end.

For example: JavaScript got data from 3rd party web service and needs to put the text into 200 x 300 px div. Text's length vary, so let's say it will take much more space than provided.

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

Upvotes: 4

Views: 144

Answers (4)

RoToRa
RoToRa

Reputation: 38431

You may also want to look into the CSS 3 property text-overflow which also does this.

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

It's possible to check if the browser supports it, so you always can add a JavaScript fall back.

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

Upvotes: 1

Michael Paulukonis
Michael Paulukonis

Reputation: 9100

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

Upvotes: 1

patorjk
patorjk

Reputation: 2182

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

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

Upvotes: 1

AndreKR
AndreKR

Reputation: 33697

There are several jQuery plugins that can do this.

Upvotes: 4

Related Questions