Limit text script

, , Leave a comment

Some times we need to limit the text in a Div and append “…show more” link at end and once the user clicks show more link, user will see full text without limit

Feel free to use the plugin the way you want. Leave a comment in case you like it or if you have any input

   /*  
   * plugin to limit the text and add ShowMore link incase the text exceeds the limit  
   * on click of the link full text   
   */  
   $.fn.limitText = function(options) {  
     /*set up the defaults*/  
     var defaults = {  
       showMoreText: '...Show more',  
       chartLimit: 30,  
       fullText: ''  
     };  
     /*extend the defaults*/  
     var options = $.extend(defaults, options);  
     return this.each(function() {  
       var $elem = $(this);  
       var text = '';  
       /*  
       * validation if the plugin is already attached, dont attach again  
       */  
       if ($elem.attr('limitTextAttached')) {  
         return;  
       }  
       /*set the attribute to the element to avoid multiple attachement of the plugin*/  
       $elem.attr('limitTextAttached', 'attached');  
       /*  
       * incase text of the element need to be used to trim   
       * if the options.fullText is specified then it will be used to trim   
       * and to append in the element  
       */  
       if ($.trim(options.fullText).length == 0) {  
         options.fullText = $elem.text();  
       }  
       text = options.fullText;  
       /*check if the text length is greater than charlimit specified*/  
       if (text.length > options.chartLimit) {  
         text = text.substring(0, (parseInt(options.chartLimit) - 1));  
         $elem.html("");  
         $elem.append(text);  
         var showMoreLink = $("<a href='#'>" + options.showMoreText + "</a>").appendTo($elem);  
         showMoreLink.click(function() {  
           $elem.html(options.fullText);  
         });  
       }  
       else {  
         $elem.html(options.fullText);  
       }  
     });  
   }  

use it like

$("#someDiv").limitText({fullText: 'hello world!!!!!'});

or if someDiv element already has any text in it then use it like simply

$("#someDiv").limitText()