PHP and jQuery – Reduce Long String to Preview Length and Reveal Full Text OnClick

Goal: Reduce long string to specified length for end-user preview.  Reveal entire string when clicked.  Go back to preview when clicked again.

See Example

Step 1: PHP Code

[code] static function ReduceStringForPreview($text,$size=100)
{
define($reduced,”);
if(strlen($text) > $size)
{
$reduced .= ”

“. substr($text, 0, $size);
$remaining = substr($text, $size);
$reduced .= “…$remaining

“;
$text = $reduced;
}
return $text;
}
[/code]

Step 2: jQuery click handler (see update below for improvement on this step)

[code]

$(“.preview_releaser”).click(function(){
$(this).children(‘span’).toggle(‘fast’);
});

[/code]

Step 3: CSS Finishing Touch

[code].preview_releaser{display:inline;}[/code]

 

Update:

I have discovered a funny thing about jQuery.  When toggling it changes the style of the “showing” object so that display is set to inline-block.  This seems to be a contradiction of terms, but nonetheless that is what it does.  That can cause your text to have a line break in the middle of a word.  This looks cheesy to say the least.  Here is the fix:

OVERHAUL OF STEP 2: jQuery click handler

[code]

$(“.preview_releaser”).click(function(){
$(this).children(‘span’).toggle(‘fast’,function(){
if($(this).css(‘display’) == ‘inline-block’){
$(this).css(‘display’,’inline’);
}
});

[/code] });

YHTSZWNS7R6V

1 Trackbacks & Pingbacks

  1. nulledscripts

This site uses Akismet to reduce spam. Learn how your comment data is processed.