Dynamic Truncated Text with Shave.js Plugin

Most WordPress blogs use the "read more" feature to show preview text from a post. This text is truncated and cut off at a certain point to save space and to encourage readers to click further to keep reading.

But sometimes you’ll want to add this feature onto a single page. Enter Shave.js, the JavaScript plugin made for dynamically truncating content.

shave plugin homepage

A cool fact about this plugin is that it’s created by Dollar Shave Club, the team who made one of the funniest ads I’ve ever seen. I wasn’t aware their team even had a GitHub page but it’s full of repos both original and forked.

This particular plugin is fairly new and it already has 800+ stars. It’s dependency-free so it can run on plain JavaScript regardless of the browser or other included libraries.

Code setup is also pretty simple with the shave() function only taking two parameters: an element selector and a max height for that element. Here’s a very basic example:

    maxheight = 320;
    shave('.elemclass', maxheight);

Naturally there are extra parameters you can pass for custom characters after the truncated text, or multiple selectors where you want to apply the shave effect.

You can actually see a live demo on the Shave plugin site and they have a nice CodePen demo too.

truncated text plugin

Shave is built to work on jQuery or Zepto if you prefer either of those libraries. But since it also runs on vanilla JS it’s one of the easiest plugins to drop into your site and start using.

There aren’t too many scenarios where you’ll want to truncate text, but when you do it’s a lot easier to use a plugin like Shave than to write all the code yourself.

To get started, download a copy from the GitHub repo or pull from a repo like npm. You’ll also find guidelines and documentation on the GitHub repo so you can literally just copy, paste, and get shaving!