Objective
- Reduce long text to six words, with a "...show more"
- Way to collapse the text again after being expanded
Summary
I want to cut the text to show a ".. read more" link that expands the content. This should cut off based on the number of words, not characters. I want to display only the first 6 words.
I also need to expand the collapse the text again by clicking a "show less" button.
Current state
I have this working on my development site, but I had to cut to 36 which is an approximation to get to 6 words. I set up this demo on codepen
Previous research
I searched various similar questions but address how to collapse based on characters, not word count. For example, Using javascript substring() to create a read more link
And I read this but unclear as to how to integrate that back into my project: javascript shorten string without cutting words
Code
HTML
<p class="ticket-text">Bacon ipsum dolor amet beef ribs shankle shoulder, chicken meatloaf andouille meatball. Filet mignon pork tenderloin prosciutto porchetta andouille, strip steak tri-tip biltong beef ribs shoulder doner t-bone alcatra kevin.</p>
Javascript
$(function(){
$('.ticket-text').each(function(event){
var max_length = 36;
if($(this).html().length > max_length){
var short_content = $(this).html().substr(0,max_length);
var long_content = $(this).html().substr(max_length);
$(this).html(short_content+
'<a href="#" class="read_more">...<br>[Read More]</a>'+
'<span class="more_text" style="display:none;">'+long_content+'</span>');
$(this).find('a.read_more').click(function(event){
event.preventDefault();
$(this).hide();
$(this).parents('.ticket-text').find('.more_text').show();
});
}
});
});