More/Less text feature: make a version that returns string

so you can use it in table_row() etc.
This commit is contained in:
David Anderson 2024-04-26 20:34:02 -07:00
parent 9b0bf3282e
commit 655f81735b
1 changed files with 20 additions and 15 deletions

View File

@ -24,48 +24,53 @@
// $text can't contain HTML tags (else would have to do lots of parsing) // $text can't contain HTML tags (else would have to do lots of parsing)
// //
function show_text_more($text, $nchars) { function show_text_more($text, $nchars) {
echo show_text_more_aux($test, $nchars);
}
// same, but returns text rather than outputting it
//
function show_text_more_aux($text, $nchars) {
static $count = 0; static $count = 0;
$n = strlen($text); $n = strlen($text);
if ($n < $nchars) { if ($n < $nchars) {
echo $text; return $text;
return;
} }
// find where to break // find where to break
$b = strpos($text, ' ', $nchars); $b = strpos($text, ' ', $nchars);
if ($b === false) { if ($b === false) {
echo $text; return $text;
return;
} }
// don't break if tail is short // don't break if tail is short
if (($n - $b) < 40) { if (($n - $b) < 40) {
echo $text; return $text;
return;
} }
$x = '';
if ($count == 0) { if ($count == 0) {
more_text_script(); $x .= more_text_script();
} }
echo substr($text, 0, $b); $x .= substr($text, 0, $b);
echo sprintf('<span id="dots_%d">...</span>', $count); $x .= sprintf('<span id="dots_%d">...</span>', $count);
echo sprintf('<span id="more_%d">', $count); $x .= sprintf('<span id="more_%d">', $count);
echo substr($text, $b); $x .= substr($text, $b);
echo '</span>'; $x .= '</span>';
echo sprintf( $x .= sprintf(
'<a onclick="toggle_more(\'dots_%d\', \'more_%d\', \'btn_%d\')" id="btn_%d"> (more)</a>', '<a onclick="toggle_more(\'dots_%d\', \'more_%d\', \'btn_%d\')" id="btn_%d"> (more)</a>',
$count, $count, $count, $count $count, $count, $count, $count
); );
echo sprintf(' $x .= sprintf('
<script>document.getElementById("more_%d").style.display = "none";</script> <script>document.getElementById("more_%d").style.display = "none";</script>
', ',
$count $count
); );
$count++; $count++;
return $x;
} }
function more_text_script() { function more_text_script() {
echo ' return '
<script> <script>
function toggle_more(dots_id, more_id, btn_id) { function toggle_more(dots_id, more_id, btn_id) {
var dots = document.getElementById(dots_id); var dots = document.getElementById(dots_id);