Advertisement
MrPauloeN

Hide/show more text within a certain length (like youtube)

Sep 23rd, 2018
161
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.    
  2. jQuery( document ).ready( function( $ ){   
  3.    
  4.         /* to make sure the script runs after page load */
  5.  
  6.     $('.item').each(function(event){ /* select all divs with the item class */
  7.  
  8.       var max_length = 150; /* set the max content length before a read more link will be added */
  9.  
  10.       if($(this).text().length > max_length){ /* check for content length */
  11.  
  12.         var short_content   = $(this).text().substr(0,max_length); /* split the content in two parts */
  13.         var long_content  = $(this).text().substr(max_length);
  14.  
  15.         $(this).html(short_content+'<br/><a href="#" class="read_more">Show More</a>'+
  16.                '<span class="more_text" style="display:none;">'+long_content+'</span>'+'<a href="#" class="read_less" style="display:none;">Show Less</a>'); /* Alter the html to allow the read more functionality */
  17.  
  18.         $(this).find('a.read_more').click(function(event){ /* find the a.read_more element within the new html and bind the following code to it */
  19.  
  20.           event.preventDefault(); /* prevent the a from changing the url */
  21.           $(this).hide(); /* hide the read more button */
  22.           $('.read_less').show(); /* show read less button */
  23.  
  24.           $(this).parents('.item').find('.more_text').show(); /* show the .more_text span */
  25.  
  26.         });
  27.  
  28.         $(this).find('a.read_less').click(function(event){
  29.           event.preventDefault();
  30.  
  31.           $(this).hide(); /* hide the read more button */
  32.           $('.read_less').hide();
  33.           $('.read_more').show();
  34.  
  35.           $(this).parents('.item').find('.more_text').hide();
  36.  
  37.         });
  38.  
  39.       }
  40.  
  41.     });
  42.    
  43.    
  44.    
  45. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement