Limit number of Characters in Div with jQuery or CSS

Glenn Glenn's Blog 10 Comments

A quick snippet for you to limit the number of characters in a span / div etc by a particular value. This function also includes a slightly neater … at the cutoff point:-


<script type="text/javascript">// <![CDATA[
$(function(){
  $(".your-div").each(function(i){
    len=$(this).text().length;
    if(len>80)
    {
      $(this).text($(this).text().substr(0,80)+'...');
    }
  });
});
// ]]></script>

Make sure you enter the character value in twice (currently 80).

Limit Number of Characters with CSS

Actually this can also be done very neatly with the ‘ellipsis’ CSS function, but note that this is relatively new and only works on single lines:-

[css]
.your-div {
white-space: nowrap;
width: 150px;
overflow: hidden;
text-overflow: ellipsis;
}
[/css]

Its the ‘text-overflow: ellipsis;’ that does all the work, but you do need the other lines for it to work effectively. Then you’ll get the same effect like ‘text stops here …’

About the Author
limit number of characters in div with jquery or css Limit number of Characters in Div with jQuery or CSS 0da77002febbfe28d15144a57bbcc2c9 s 180 d mm r g

Glenn

A highly experienced WordPress Web Developer, Front-end and Back-end Developer & New Media Specialist with extensive knowledge of a wide spectrum of technologies in the Development and Creative Industries built up over a number of years.

Comments 10

  1. This is great! One question: is it possible to somehow ensure that words are not cut off? What would I add to make that happen?

    Otherwise, works like a charm!

  2. Post
    Author

    Nice to see a fellow Glenn with x2 n’s…. in answer to your question we have looked into solutions for this, but so far nothing lightweight. Perhaps others can spread light on getting jQuery to preserve whole words?

    1. It seems i found one lightweight solution with indexOf:

      len=$(this).text().length;
      limit=$(this).text().indexOf(" ", 230);
      if(len>250)
      {
      $(this).text($(this).text().substr(0,limit)+'...');

  3. Hi nice post about truncating a text string with use of text-overflow:elipsis in css. But i have a problem using this where i want to chop my text exactly after 23 characters. Now the text-overflow is working for me after i set the width:160px , but the problem is that the position where the elipsis are being appended depends on the font style & font size of the characters as well. I mean “abcd-1234” and “ABCD-1234” both have same number of characters but the width: applies differently to each of them. Is there any way to chop the string exactly after lets say 10 characters and the apply
    text-overflow:elipsis to it?

  4. you can do this with css also]


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

Leave a Reply

Your email address will not be published. Required fields are marked *