10

Can i hide text in a DIV after a number of characters with jQuery?

So far I think it would go something like this - jQuery would cycle through the text until it gets to a certain number of characters. It would then wrap a DIV from that position to the end of the text which could then be hidden with the hide() method. I'm not sure how to insert that wrapping text.

Any other way around this would also be appreciated.

Thanks.

usertest
  • 27,132
  • 30
  • 72
  • 94
  • You mentioned in a comment below that the content you are trying to limit may have text and html tags. Are those tags standardized or do you need a dynamic solution? Also.. will there be multiple child tags with text in each? I think those are important factors. – jessegavin Nov 12 '09 at 17:18
  • I think the only tags with the text will be
    tags.
    – usertest Nov 12 '09 at 17:34
  • You may wish to look at the answers [here](http://stackoverflow.com/questions/536814/javascript-insert-ellipsis-into-html-tag-if-content-too-wide). – Paddy Nov 12 '09 at 16:50
  • Its not the physical width I want to limit it by, its the number of characters. – usertest Nov 12 '09 at 16:52

7 Answers7

21

I think the purpose can be solved much more easier way than explained above

$(function(){
  $(".title").each(function(i){
    len=$(this).text().length;
    if(len>10)
    {
      $(this).text($(this).text().substr(0,10)+'...');
    }
  });       
});

The above jquery code will hide div text if it exceeds 10 characters as well as ads ... at the end to explain that there is something more.

alony
  • 10,725
  • 3
  • 39
  • 46
Swadesh
  • 651
  • 2
  • 8
  • 22
  • I switched to this from the answer, as i only needed it applied IF the text limit it hit. Also this is less code. Thanks for this great answer +1 – Gerico Aug 13 '12 at 16:19
  • add a trim() for difficult text. –  Nov 02 '13 at 07:59
  • what about when working with wordpress? I Have tried this function to limit the span class 'rs_rs_name' to 45 characters, but its not working.. any ideas? `jQuery(function(){ jQuery(".rs_rs_name").each(function(i){ len=$(this).text().length; if(len>45) { jQuery(this).text($(this).text().substr(0,45)+'...'); } }); });` – RobBenz Aug 13 '15 at 19:22
11

This will hide a part of the text

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

    <title>untitled</title>
    <style type="text/css" media="screen">
        .hide{
            display: none;
        }
    </style>
    <script src="js/jquery-1.3.2.min.js" type="text/javascript" charset="utf-8"></script>
    <script type="text/javascript" charset="utf-8">
        $(function(){
            var $elem = $('p');         // The element or elements with the text to hide
            var $limit = 10;        // The number of characters to show
            var $str = $elem.html();    // Getting the text
            var $strtemp = $str.substr(0,$limit);   // Get the visible part of the string
            $str = $strtemp + '<span class="hide">' + $str.substr($limit,$str.length) + '</span>';  // Recompose the string with the span tag wrapped around the hidden part of it
            $elem.html($str);       // Write the string to the DOM 
        })
    </script>

</head>
<body>
<p>Some lenghty string goes here</p>
</body>
</html>
zyON
  • 126
  • 3
  • Hi thanks for the reply but it has the same problem as jessegavin's code, HTML tags are not ignored. So sometimes half of a tag shows up in the output. – usertest Nov 12 '09 at 17:32
  • 1
    I can't comment jessegavin's answer, but here's the way to get it working in multiple divs: Put the jQuery code inside this: $('.someClass').each(function(){ // Code goes here }); and make the change: "#myDiv" To this – zyON Nov 12 '09 at 18:52
2
$.fn.textlimit = function(limit)
{
    return this.each(function(index,val)                       
    {
        var $elem = $(this);
        var $limit = limit;
        var $strLngth = $(val).text().length;  // Getting the text
        if($strLngth > $limit)
        {
          $($elem).text($($elem).text().substr( 0, $limit )+ "...");
        }
    })
};

**how to use**

$("#DivId").textlimit(60);
Tameshwar
  • 789
  • 1
  • 10
  • 17
2

Jeff I was having the same issue wanted to add the text limiter to a dynamic content so here is my solution:

// TEXT CHARACTER LIMITER 

$(document).ready(function() {

  $.fn.textlimit = function()
  { 

    return this.each(function()                       
    {

    var $elem = $(this);            // Adding this allows u to apply this anywhere
    var $limit = 22;                // The number of characters to show
    var $str = $elem.html();        // Getting the text
    var $strtemp = $str.substr(0,$limit);   // Get the visible part of the string
    $str = $strtemp + '<span class="hide">' + $str.substr($limit,$str.length) + '</span> ...';  
    $elem.html($str);
    })

  };

});

// Call the text limiter above 

$(document).ready(function() {

    $('.someGenericClass .anotherClass').textlimit()

});
Andrei Sfat
  • 8,440
  • 5
  • 49
  • 69
Bert
  • 21
  • 2
1

I am replacing my original answer with this one.....

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
    $(function() {
        var limit = 20;
        var chars = $("#myDiv").text(); 
        if (chars.length > limit) {
            var visiblePart = $("<span> "+ chars.substr(0, limit-1) +"</span>");
            var dots = $("<span class='dots'>... </span>");
            var hiddenPart = $("<span class='more'>"+ chars.substr(limit-1) +"</span>");
            var readMore = $("<span class='read-more'>Read More</span>");
            readMore.click(function() {
                $(this).prev().remove(); // remove dots
                $(this).next().show();
                $(this).remove(); // remove 'read more'
            });

            $("#myDiv").empty()
                .append(visiblePart)
                .append(dots)
                .append(readMore)
                .append(hiddenPart);
        }
    });
</script>
<style type="text/css">
    span.read-more { cursor: pointer; color: red; }
    span.more { display: none;  }
</style>
</head>
<body>
    <div id="myDiv">Here are all<br/> my characters.<br/> I would like to limit them to 20.</div>
</body>
</html>
jessegavin
  • 74,067
  • 28
  • 136
  • 164
  • 1
    Your `len` variable is a bit hanging around =) – BalusC Nov 12 '09 at 17:07
  • Hi, thanks but unfortunately the DIV text does contain HTML tags as i'm getting it from an external API. – usertest Nov 12 '09 at 17:08
  • As far as I can tell there are only
    tags in my text, is there any way to skip them in your code? Thanks.
    – usertest Nov 12 '09 at 17:14
  • BalusC. Yup I saw that and removed it. Good catch. +1 – jessegavin Nov 12 '09 at 17:14
  • The second parameter to substr() is length, not end index, so I'm guessing you actually mean chars.substr(0, limit). – Lobstrosity Nov 12 '09 at 17:59
  • substr() doesn't care if the specified length is longer than the string, so for brevity you could just say $("#myDiv").text($("#myDiv").text().substr(0, 15)); – Lobstrosity Nov 12 '09 at 18:00
  • Excellent! But may I ask one more question. I tried changing myDiv to a class and applying it to multiple DIV's but it won't work. I tried using the each function but that doesn't seem to work. Any idea what the problem could be? – usertest Nov 12 '09 at 18:22
0

If you put a onkeydown event handler on the body tag you can then count the length in the div of interest, and then you can hide it when done, and remove your event handler.

James Black
  • 41,583
  • 10
  • 86
  • 166
0

HTML :

25 is maxlength.

<input type="text" name="Occupation"  id="Occupation" value="" placeholder=""
onkeypress="limitKeypress(event,this.value, 25)" class="form-control" required>
                                    

Javascript:

function limitKeypress(event, value, maxLength) {
        if (value !== undefined && value.toString().length >= maxLength) {
            event.preventDefault();
        }
    }