Skip to content

Instantly share code, notes, and snippets.

@aradnom
Created February 21, 2014 23:44
Show Gist options
  • Save aradnom/9146076 to your computer and use it in GitHub Desktop.
Save aradnom/9146076 to your computer and use it in GitHub Desktop.
Ellipsize text in a container with elements. Note that the base function only looks at text, so it's possible to split an inline element. Example of use included.
// Example of ellipsizing
$( function () {
var ellipsis_length = 10;
// Ellipsize text
var text_elements = $('.promotion__content__text *');
// Flip through content elements looking for ellipsis boundary
var boundary = null;
text_elements.each( function() {
// If ellipsized text is returned, make the boundary here and hide all other elements
// Otherwise do nothing
if ( boundary ) {
// If earlier element is boundary, just hide this element
$(this).addClass( 'ellipsized__hidden' ).hide();
} else {
var ellipsized = ellipsize( $(this).text(), ellipsis_length );
if ( ellipsized ) {
boundary = $(this);
// Clip the text by injecting the ellipsized text instead
var after = $('<span/>', { html: ellipsized.after, 'class': 'ellipsized__hidden' }),
ellipsis = $('<span/>', { text: '...', 'class': 'ellipsized__dots' });
$(this).html( ellipsized.before );
$(this).append( ellipsis, after );
after.hide();
}
}
});
// Show full content text
$('.promotion__content__read-more').click( function ( event ) {
event.preventDefault();
$('.ellipsized__dots').hide();
$('.ellipsized__hidden').show();
});
});
// Basic function
// Returns object containing BEFORE text and AFTER text
function ellipsize ( text, length ) {
var regex = /\s/gi,
match,
count = 0;
if ( text && text.length ) {
while ( match = regex.exec( text ) ) {
count++;
if ( count == length ) {
var cut_index = match.index;
break;
}
}
if ( cut_index ) {
var split = text.split( '' );
return {
before: split.splice( 0, cut_index ).join(''),
after: split.splice( 0, split.length ).join('')
};
}
}
// If text does not need to be ellipsized, just return nothing
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment