How to create a read more and read less option for page description using JS

| | 2 min read

Now a days for almost all the website have atleast one read more option. Read more options are mainly for excluding the full content of a text or a paragraph to improve its visibility for the user. By the read more option user gets the freedom to view the full content if the user wants.

If we are using Drupal views modules there already exists here i am discussing "How to get a custom read more option for a text or a paragraph using css alone".

I have faced a situation where i can't able to use any other method except java-script. If anyone is facing this situation the below codes will surely helps to fix the issue.

I have a Drupal page with a description with a huge number of lines and i need to display the description along with a read more after a particular character limit for the visibility of the page. I need to display first 800 character along with a read more option and also a read less option to hide to the maximum character.

/* Read more and read less option for the description 1 */

var minimized_elements = $("#description_first");
var minimize_character_count = 800;    

minimized_elements.each(function(){    
  var t = $(this).text();        
  if(t.length < minimize_character_count ) return;

  $(this).html(
      t.slice(0,minimize_character_count )+
      '<span>... </span><a href="#" class="read_more">Read more</a>'+
      '<span style="display:none;">'+ t.slice(minimize_character_count ,t.length)+
      '<a href="#" class="read_less">Read less</a></span>'
    );  
});

$('a.read_more', minimized_elements).click(function(event){
  event.preventDefault();
  $(this).hide().prev().hide();
  $(this).next().show();        
});

$('a.read_less', minimized_elements).click(function(event){
  event.preventDefault();
  $(this).parent().hide().prev().show().prev().show();    
});

The above code works fine for me add a read more and read less option with the character count.

We can also improve the style of read more and read less by adding a background image of with custom css styles including background color along with box shadow etc.

Add the below line to style the read more and read less links

.read_more, read_less {  
  background-color: #808080;
  border-radius: 5px;
  box-shadow: 3px 1px 5px #888888;
  color: #333333;
  font-family: 'Merriweather-BoldItalic';
  font-size: 1px;
  height: 30px;
  text-decoration: none;
  width: 100px;
}