Swadesh
Swadesh

Reputation: 651

How to wrap content of div and add … at the end?

I've a div which displays content. My requirement is if it exceeds 10 characters it must show

10 characters + '...'

I can use jQuery as well as PHP.

Upvotes: 0

Views: 154

Answers (2)

rapaelec
rapaelec

Reputation: 1330

If you use php you can use the function substr($text, $start, $length), the doc here like this:

<?php

$test = "Lorem ipsum dolor sit amet consectetur adipisici";
// fonction to split the part of text if necessary
$result = strlen($test)>10 ? substr($test, 0, 10).'....': $test;
// to display the text: and don't check the length of string
echo $result;

so in jQuery , you have too fonction substr the doc : here like that:

$(document).ready(function() {
 let text = "Lorem ipsum dolor sit amet consectetur adipisici"
 let result = text.length > 10 ? text.substr(0, 10)+"..." : text;
 
 alert(result);
});

I hope it's help you

Upvotes: 0

Flavio Cysne
Flavio Cysne

Reputation: 1456

To restrict text shown to only, and specifically, 10 characters will be tricky as you'll need to calculate text width based on font settings.

If you use an unit like em you won't need to bother this and the text shown will be almost the same width you desire.

There is an editable example of this:

http://jsfiddle.net/flaviocysne/88nLY/2/

Based on these sites examples:

http://www.quirksmode.org/css/textoverflow.html

http://davidwalsh.name/css-ellipsis

Upvotes: 1

Related Questions