Skip to content

Instantly share code, notes, and snippets.

@jdrzejb
Created November 23, 2020 20:07
Show Gist options
  • Save jdrzejb/6e2ddb27cea978723276bd0abe03e88c to your computer and use it in GitHub Desktop.
Save jdrzejb/6e2ddb27cea978723276bd0abe03e88c to your computer and use it in GitHub Desktop.
Truncate text
# This function truncates multiple line texts
# @pre - set 'line-height' prop for container
# @param container - jQuery elem holding the text
# @param text - text to truncate
# @param lines - number of text lines in container
truncateText: (container, text, lines) ->
container.text text
maxHeight = lines * parseFloat container.css 'line-height'
# return original text w/o '...'
return text if container.innerHeight() <= maxHeight
# remove word by word and check the new height
truncatedText = container.text()
while container.innerHeight() > maxHeight
truncatedText = truncatedText.replace /\s.[^\s]*\s?$/, ''
container.text truncatedText
truncatedText.substr(0, truncatedText.length - 3) + '\u2026' # <- '...'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment