jQuery.fn.truncate = function( max, settings ) { settings = jQuery.extend( { chars: /\s/, trail: [ "...", "" ] }, settings ); var myResults = {}; var ie = jQuery.browser.msie; function fixIE( o ) { if ( ie ) { o.style.removeAttribute( "filter" ); } } var original_max = max; return this.each( function() { // var this = jQuery(this); var myStrOrig = jQuery(this).html().replace( /\r\n/gim, "" ); var myStr = myStrOrig; var myRegEx = /<\/?[^<>]*\/?>/gim; var myRegExArray; var myRegExHash = {}; var myResultsKey = jQuery("*").index( this ); while ( ( myRegExArray = myRegEx.exec( myStr ) ) != null ) { myRegExHash[ myRegExArray.index ] = myRegExArray[ 0 ]; } myStr = jQuery.trim( myStr.split( myRegEx ).join( "" ) ); if ( myStr.length > original_max ) { var c; while (( max < myStr.length ) && ( max > 0)) { c = myStr.charAt( max ); if ( c.match( settings.chars ) ) { myStr = myStr.substring( 0, max ); break; } max--; } if ( max == 0 ) { myStr = myStr.substring( 0, original_max ); } if ( myStrOrig.search( myRegEx ) != -1 ) { var endCap = 0; for ( eachEl in myRegExHash ) { myStr = [ myStr.substring( 0, eachEl ), myRegExHash[ eachEl ], myStr.substring( eachEl, myStr.length ) ].join( "" ); if ( eachEl < myStr.length ) { endCap = myStr.length; } } jQuery(this).html( [ myStr.substring( 0, endCap ), myStr.substring( endCap, myStr.length ).replace( /<(\w+)[^>]*>.*<\/\1>/gim, "" ).replace( /<(br|hr|img|input)[^<>]*\/?>/gim, "" ) ].join( "" ) ); } else { jQuery(this).html( myStr ); } myResults[ myResultsKey ] = myStrOrig; jQuery(this).html( [ "
", jQuery(this).html(), settings.trail[ 0 ], "
" ].join( "" ) ) .find(".truncate_show",this).click( function() { if ( jQuery(this).find( ".truncate_more" ).length == 0 ) { jQuery(this).append( [ "" ].join( "" ) ) .find( ".truncate_hide" ).click( function() { jQuery(this).find( ".truncate_more" ).css( "background", "#fff" ).fadeOut( "normal", function() { jQuery(this).find( ".truncate_less" ).css( "background", "#fff" ).fadeIn( "normal", function() { fixIE( this ); jQuery(this).css( "background", "none" ); }); fixIE( this ); }); return false; }); } jQuery(this).find( ".truncate_less" ).fadeOut( "normal", function() { jQuery(this).find( ".truncate_more" ).fadeIn( "normal", function() { fixIE( this ); }); fixIE( this ); }); jQuery(".truncate_show",jQuery(this)).click( function() { jQuery(this).find( ".truncate_less" ).css( "background", "#fff" ).fadeOut( "normal", function() { jQuery(this).find( ".truncate_more" ).css( "background", "#fff" ).fadeIn( "normal", function() { fixIE( this ); jQuery(this).css( "background", "none" ); }); fixIE( this ); }); return false; }); return false; }); } }); };