pedritoalfonso
pedritoalfonso

Reputation: 183

Shrink a text if more than 10 characters length

Hi I have the Following <h2> "Example example example example". I want to detect the lenght of this <h2> and if it's more than 10 characters, shrink it to "Example ex...". Get it? Shrink it to 10 characters long and add "..." to the end.

Here's my code:

HTML

<h2>Example example example example example</h2>
<h2>Example</h2>

jQUERY

$(document).ready(function(){
    var dtl = $('.h2').text().length;

        if(dtl>10){
        $('.h2').text().length = 10;
        $('.h2').text($('.h2').text()+"...");
    } 
});

But that's not working...

Upvotes: 3

Views: 2991

Answers (3)

Lavanya Ram
Lavanya Ram

Reputation: 11

Try this code,it may works

<h2>This tag contains more than 10 characters</h2>

Jquery:

$(document).ready(function () {
        var len = $("h2").text().length;
        var text = $("h2").text();

        if (len > 10) {
            var stext = text.substring(0, 10);
            $("h2").text(stext).append("...");
        }

    });

Upvotes: 0

Sahil Sharma
Sahil Sharma

Reputation: 2017

You have two <h2> tags you will have to use

$("h2").each(function() {
   var dtl = $(this).text().length;
   //rest of your code goes here
   if(dtl>10){
      var res = $(this).text();
      res = res.substring(0, 4); //apply your logic here what ever you want pass (0, 10)
     $(this).text(res +"...");
   } 
});

Upvotes: 2

mohamedrias
mohamedrias

Reputation: 18576

You need to use substr in this case:

And you have h2 tag elements and not .h2 classname.

$(document).ready(function(){
    var dtl = $("h2").text().length;

     if(dtl>10){
        $('h2').text($('h2').text().substr(0,10)+"...");
    } 
});

Am doing just for one element, you may need to use $("h2").each() to target all the elements.

More complete code:

 $(document).ready(function(){

         $("h2").each(function() {
             if($(this).text().length > 10) {
               $(this).text($(this).text().substr(0,10)+"...");
             }
         });
    });

DEMO

 $(document).ready(function(){

     $("h2").each(function() {
         if($(this).text().length > 10) {
           $(this).text($(this).text().substr(0,10)+"...");
         }
     });
});
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
<h2>Example example example example example</h2>
<h2>Example</h2>
</body>
</html>

Upvotes: 4

Related Questions