Versatile jQuery Plugin For Truncating Text - Truncate.js

File Size: 23.4 KB
Views Total: 282
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
Versatile jQuery Plugin For Truncating Text - Truncate.js

A lightweight and flexible JavaScript/jQuery plugin that allows you to truncate text content on a webpage based on the number of lines you specify.

It provides the option to truncate text at the beginning, middle, or end, allowing you to choose the most appropriate method for your content.

How to use it:

1. Add the Truncate.js script to your HTML page. jQuery is OPTIONAL.

<!-- jQuery is OPTIONAL -->
<script src="/path/to/cdn/jquery.min.js"></script>

<!-- jQuery is OPTIONAL -->
<script src="/path/to/dist/truncate.min.js"></script>

2. Initialize the plugin on your long text content. In the example below, the text within the element with the class "demo" will be truncated to 3 lines, with the truncation occurring in the middle of the text. An ellipsis will be added to indicate truncation.

<div class="demo">
  Your Content Here
// As a jQuery plugin
  lines: 3, // default: 1
  position: 'middle', // default 'end'

// Vanilla JS 
const truncated = new Truncate(document.getElementById('#demo'), {
  lines: 3,
  position: 'middle',

3. More plugin options.


  // set the string to indicate that the text has been truncated
  ellipsis: '…',

  // show more/less text
  showMore: '',
  showLess: '',
  // line height in px
  lineHeight: 'auto',

  // truncate the text to fit in the specified height
  maxHeight: undefined,

4. API methods.

// jQuery
// Update the HTML and truncate.
$('#demo').truncate('update', 'new content to truncate');

// expand the content

// collapse the content
// Vanilla JS 
// Update the HTML and truncate.
truncated.truncate('update', 'new content to truncate');

// expand the content

// collapse the content

// check if is truncated

// check if is collapsed

This awesome jQuery plugin is developed by jeffchan. For more Advanced Usages, please check the demo page or visit the official website.