Truncating text for smooth looking content
There are 4 standard methods of limiting text content: 1. Limit the amount of characters within a text field or else where. 2. Trim text server-side 3. Use CSS with
text-overflow: ellipsis. 4: Clamp lines with
Standard methods of limiting text content
Limiting the amount of characters can be a good way to police text length to make sure it is concise. The down side of limiting characters is that it can greatly effect content. A both positive and negative example of limiting text is writing a tweet in twitter. It is often great for forcing the tweeter to write concisely but it is also limiting sometimes.
<title>We went to the store and we found that grapes</title> <!-- This doesn't make sense -->
Trimming text before it is rendered on a webpage is a very efficient way to ensure that text is a certain length but there is no way to ensure that the result is legible.
<title>We went to the store and we found that grapes were...</title> <!-- This doesn't make sense -->
Text-overflow: ellipsis fixes most of these scenarios because text will just not be shown after a single line and an ellipsis gets adds by the browser to suggest that there is more to read.
<h1 style="text-overflow: ellipsis">We went to the store and we found that grapes were on sale. Go purchase grapes today!</h1> <!-- If the text extends beyond 1 line this title will be unreadable -->
Implementing a Binary Search
After feedback on reddit that truncation performance is often an issue when performed on many elements we implemented binary search. Binary search is a process of splitting things in half repeatedly to more quickly get to an exact result. After implemention of this we've found that Shave can trim a lot of text pretty fast.
Why do we use max-height?
We've received requests to figure out the height of what needs to be truncated based on lines. By using
max-height we felt that the developer could more easily calculate the height of a number of lines which makes the plugin to be considerably lighter. Shave is not a polyfill for Line Clamp which will be fully supported soon. Shave's goal is to be the most efficient Dom Element truncation plugin for edge cases detailed above.
What Shave does
Shave, 1. maintains the original text after truncation, 2. has no dependencies, 3. only requires a selector and a max height and is very lightweight (~1.5kb unminified), 3. allows for custom ellipsis strings and class names but doesn't over complicate, 4. is fast and capable of truncating text within lots of elements quickly and 5. supports non-spaced languages (Non-ascii).
Shave compared to other truncation plugins
Shave compiles 50 long paragraphs pretty fast:
Text truncation in the future
Currently the css rule line clamp, which truncates text to a certain number of lines, is implemented in Safari and Chrome. If it is implemented globally we would recommend switching from Shave to line-clamp but until then use Shave.