Skip to content

Instantly share code, notes, and snippets.

@localpcguy
Created September 28, 2015 20:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save localpcguy/fc1e42153407977ef52a to your computer and use it in GitHub Desktop.
Save localpcguy/fc1e42153407977ef52a to your computer and use it in GitHub Desktop.
Truncate Multiline Copy
<div class="cropContainer">
<div class="cropCopy">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam elit risus, tempor vel faucibus vel, tempor scelerisque nisi. Nullam quis odio venenatis, tempus ligula a, viverra magna. Vestibulum tincidunt risus nisl, id maximus leo venenatis eu. Pellentesque accumsan purus ut ipsum pellentesque pulvinar nec ac ex. Integer pretium enim erat, ut varius nunc fringilla in. Nulla ornare venenatis nisl, ac ultricies lorem pretium ut. Sed lacinia eget lacus ut consequat</div>
</div>
/**
* truncateCopy - truncate multiline text at the end of a known
* height outercontainer and add an ellipsis (or other)
* @param {string} content selector to get the inner container
* @param {string} contentContain selector to get the outer container that has a known height
* @param {string} contentToAppend word or html string to add to the end of the truncated string
* @return {string} void
*/
function truncateCopy(content, contentContain, contentToAppend, appendAlways) {
var $content = $(content);
$content.each(adjustContentHeight);
function adjustContentHeight(index, value) {
var $contentContain = $(value).closest(contentContain);
if ($contentContain.length > 0 && $content.outerHeight() > $contentContain.outerHeight()) {
// only run if the content is larger than the container
var $theContent = $(value);
var divh = $contentContain.innerHeight();
var $editedCopyContainer;
var $editedCopyContainerText;
function textReplace(index, text) {
return text.replace(/\W*\s(\S)*$/, '');
}
do {
$editedCopyContainer = $theContent.text(textReplace);
$editedCopyContainerText = $editedCopyContainer.html();
if ($theContent.outerHeight() <= divh) {
var newString = $editedCopyContainerText.substr(0, $editedCopyContainerText.length - 20);
$theContent.html(newString + contentToAppend);
}
}
while ($theContent.outerHeight() > divh);
} else if (!!contentToAppend && appendAlways) {
// just to add to the copy, not cropping paragraph
$(value).html($(value).text() + contentToAppend);
}
}
}
// Execute
truncateCopy('.cropCopy', '.cropContainer', '&hellip;', true);
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
.cropContainer {
height: 155px;
width: 250px;
overflow: hidden;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment