Truncate Text | JavaScriptSource

Truncate Text

Patrick Fitzgerald May 16, 2007


This script is a clever way of automatically truncating the text of a paragraph, without dividing in the middle of a word. You can truncate the text to a length of your choosing. A link is added to expand the text.

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean consectetuer. Etiam venenatis. Sed ultricies, pede sit amet aliquet lobortis, nisi ante sagittis sapien, in rhoncus lectus mauris quis massa. Integer porttitor, mi sit amet viverra faucibus, urna libero viverra nibh, sed dictum nisi mi et diam. Nulla nunc eros, convallis sed, varius ac, commodo et, magna. Proin vel risus. Vestibulum eu urna. Maecenas lobortis, pede ac dictum pulvinar, nibh ante vestibulum tortor, eget fermentum urna ipsum ac neque. Nam urna nulla, mollis blandit, pretium id, tristique vitae, neque. Etiam id tellus. Sed pharetra enim non nisl.


  • Once expanded it cannot be collapsed again (but that functionality could be added just as easily).
  • It assumes that the content is plain text with no markup. If there is markup, it is taken into account when counting the text for division pueposes.

Source Code

Paste this source code into the designated areas.

External file

Paste this code into an external JavaScript file named: truncateText.js


Paste this code into the HEAD section of your HTML document.


Paste this code into the BODY section of your HTML document

Leave a Response


Hi. The code is great but 2 things. Could you not add a function that after expanding the text would collapse it again & why when using it in conjunction with a database query does it only work on the first record? Many Thanks. Ivor

Ivor Sep 11, 2007

it should contract again after its been expanded

jhn dep Jun 12, 2007

I would like to contract the paragraph as well as expand it. HOW?

marvin starvin May 29, 2007

I think if I knew how to make the argument 'truncateMe' a symbolic variable I could have many instances on the same page - solving Chris's issue. But I don't know how to do that, nor can I figure out how to create a 'Less' box in order to restore the page - and considering Chris's question in the solution would be a plus!

John Moss May 25, 2007

I am trying to use the code many times on the same page for different paragraphs, but only one paragraph appears truncated. Please help. Thanks

Chris Bartolo May 24, 2007