Multiline Text Truncator In Vanilla JavaScript – Cuttr.js

Category: Javascript , Text | December 12, 2022
Author:d-e-v-s-k
Views Total:176 views
Official Page:Go to website
Last Update:December 12, 2022
License:MIT

Preview:

Multiline Text Truncator In Vanilla JavaScript – Cuttr.js

Description:

Cuttr.js is a vanilla JavaScript text truncation library to truncate text to any number of characters, words, or even sentences.

With optional Read More/Read Less buttons, your visitors can reveal and hide overflowing text with just one click.

How to use it:

1. Install and download.

# Yarn
$ yarn add cuttr
# NPM
$ npm i cuttr --save

2. Include the minified version of the Cuttr.js library on the web page.

<script src="./dist/cuttr.min.js"></script>

3. Truncate your long text to a specific number of characters.

<p class="example" >Lorem ipsum dolor sit amet, <a href="#">link</a> consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa? Aenean commodo ligula eget dolor! Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.</p>
new Cuttr('.truncate-characters', {
    length: 30 // default: 100
});

4. Truncate your long text to a specific number of words.

new Cuttr('.truncate-characters', {
    truncate: 'words'
    length: 5 // default: 100
});

5. Truncate your long text to a specific number of sentences.

new Cuttr('.truncate-characters', {
    truncate: 'sentences'
    length: 2 // default: 100
});

6. Customize the string displayed at the end of your text after truncated. Default: ‘…’.

new Cuttr('.truncate-characters', {
    ending: '......'
});

7. Determine the CSS class to set when truncation finished.

new Cuttr('.truncate-characters', {
    loadedClass: 'cuttr--loaded'
});

8. Customize the Read More & Read Less buttons.

new Cuttr('.truncate-characters', {
    readMore: false, 
    readMoreText: 'read more',
    readLessText: 'read less',
    readMoreBtnPosition: 'after',  // or 'inside'
    readMoreBtnTag: 'button',
    readMoreBtnSelectorClass: 'cuttr-readmore', 
    readMoreBtnAdditionalClasses: '',
});

9. Determine whether to add original content to element’s title tag.

new Cuttr('.truncate-characters', {
    title: true
});

10. Callbacks.

new Cuttr('.truncate-characters', {
    afterTruncate: function(){
      // after truncate
    },
    afterExpand: function(){
      // after expand
    }
});

11. API methods.

cosnt instance = new Cuttr('.truncate-characters', {
      // ...
});
// expand content
instance.expandContent()
// truncate content
instance.truncateContent()
// destroy
instance.destroy()

Changelog:

v1.4.3 (12/12/2022)

  • update

v1.4.1 (03/02/2022)

  • update

v1.4.0 (02/17/2022)

  • added callbacks
  • update build dependencies

v1.3.1 (06/10/2021)

  • add public methods

v1.2.0 (11/11/2020)

  • add title-attr option

v1.1.2 (09/23/2020)

  • update

You Might Be Interested In:


Leave a Reply