Shave is a zero dependency javascript plugin that truncates multi-line text to fit within an html element based on a set pixel number max-height. It then stores the diff of the original text string in a hidden <span> element following the visible text. This means the original text remains intact!
Shave, compared to other truncation plugins:
maintains the original text after truncation.
does not require other libraries
only requires a selector and a max height
is very lightweight; ~1.5kb unminified
allows for custom ellipsis strings and class names but doesn't over complicate
new! provides ellipsis link functionality
is fast and capable of truncating text within lots of elements quickly
is additive. It will play nice with other javascript libraries and more truncation features can easily be built with it.
/** * @notes * - provide your desired link attributes here! * @note link attributes trump the character option and className of the ellipsis element */shave("selector", maxheight, { link: LinkObject });
You can also use shave as a jQuery or Zepto plugin. As of Shave >= v2, use dist/jquery.shave.js for jQuery/Zepto.
$("selector").shave(maxheight);
And here's a jQuery/Zepto example with custom options:
/** * @notes * - provide your desired link attributes here! * @note link attributes trump the character option and className of the ellipsis element */$("selector").shave(maxheight, { link: LinkObject });
Prefer Link Functionality
The shave plugin provides a link option—an <a> element which replaces the default <span> element.
As any functionality that is needed without an href attribute can be made using the default <span> element, the <a> is only rendered if the href attribute is provided.
Any attributes that can be used for an <a> element can be added to the link object when invoking shave.
Additionally textContent can be added to replace the default character option.
Here's a more in-depth example than the basic example(s) above:
text-overflow: ellipsis is the way to go when truncating text to a single line. Shave does something very similar to text-overflow: ellipsis but for multiple lines when line-clamp is not supported. Shave bypasses being a line-clamp polyfill by only accepting a max-height number. This keeps shave a fast and light weight utility.
Shave implements a binary search to truncate text in the most optimal way possible.
Shave is meant to truncate text within a selected html element. This means it will overwrite html within an html element with just the text within the selected element.
Here are some super basic examples of shave with window resize and click events. 🙌
Shave works in all modern browsers and was tested in some not so modern browsers (like Internet Explorer 8) - it works there too. 🍻