Thursday 20 January 2011

Limit text or Show More script

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() 

Tuesday 4 January 2011

Array Sort - Number expected in Internet Explorer

While working on sorting array for date with following code
/*sort the array with date*/
data.sort(function(a, b) {
var objA = a.date;
var objB = b.date;
var dateA = new Date(objA);
var dateB = new Date(objB);
return dateA - dateA;
});
i faced "Number expected" error in IE while it was working fine in other browsers.

Fix - Parse the return as Int like this
/*sort the array with date*/
data.sort(function(a, b) {
var objA = a.date;
var objB = b.date;
var dateA = new Date(objA);
var dateB = new Date(objB);
return parseInt(dateA - dateA);
});