user3193385 user3193385 - 6 months ago 31
HTML Question

How to limit the length of text in a paragraph

I have a paragraph as below, which may be of any length:


Breaking India: Western Interventions in Dravidian and
Dalit Faultlines is a book written by Rajiv Malhotra
and Aravindan Neelakandan which argues that India's
integrity is being undermined.


I want it to appear as:


Breaking India: Western Interventions in Dravidian and
Dalit Faultlines is a book written by Rajiv Malhotra...


below is the code which populates description in my website:





currently description goes to any no. of line based on product, i need to limit this to 3 lines.

Answer

If you want to use html and css only, your best bet would probably be to use something like:

p {
     width: 250px;
     white-space: nowrap;
     overflow: hidden;
     text-overflow: ellipsis;
}

Here is an example: http://jsfiddle.net/nchW8/ source: http://css-tricks.com/snippets/css/truncate-string-with-ellipsis/

If you can use javascript you can use this function:

function truncateText(selector, maxLength) {
    var element = document.querySelector(selector),
        truncated = element.innerText;

    if (truncated.length > maxLength) {
        truncated = truncated.substr(0,maxLength) + '...';
    }
    return truncated;
}
//You can then call the function with something like what i have below.
document.querySelector('p').innerText = truncateText('p', 107);

Here is an example: http://jsfiddle.net/sgjGe/1/