Skip to content

Instantly share code, notes, and snippets.

@mwender
Last active Aug 3, 2022
Embed
What would you like to do?
A jQuery based function for showing long blocks of text as an excerpt with a "Read more..." link.
(function($){
function hideText( textselector, strlen, moretext ){
strlen = typeof strlen !== 'undefined' ? strlen : 100;
moretext = typeof moretext !== 'undefined' ? moretext : 'Read More';
var sections = $( textselector );
for(var i = 0; i < sections.length; i++ ){
console.log( sections[i] );
var textToHide = $( sections[i] ).html();
var textToCheck = $( sections[i] ).text().substring(strlen);
if( '' == textToCheck )
continue;
var visibleText = $( sections[i] ).text().substring(0, strlen);
$( sections[i] )
.html(('<span class="visible-text">' + visibleText + '&hellip;</span>') + ('<span class="hidden-text">' + textToHide + '</span>'))
.append('<span class="read-more"><a title="' + moretext + '" style="cursor: pointer;">' + moretext + '</a></spam>')
.click(function() {
$(this).find('span.hidden-text').toggle();
$(this).find('span.read-more').toggle();
$(this).find('span.visible-text').toggle();
});
$( sections[i] ).find( 'span.hidden-text' ).hide();
}
}
hideText( 'div.hidetext', 200, 'Read More &rarr;' );
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment