1

I am trying to limit an element's characters to 90 words normally. But when the show more button is clicked it should remove the limit.

I tried using a class to do this and attaching the limit to the class and then removing the class when the show more button is clicked.

My attempt at this:

        <header>
           <h1>Heading Goes Here</h1>
           <p class="jumbo-p non-exp">
               The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog.
           </p>
           <a href="#" class="more1">more</a>
       </header> 

The CSS:

     .jumbo-p{display: inline-block; height: 20px; overflow: hidden;}
     .more1 {position: relative; left: 2px; top: -21px;}
     .jumbo-p.expanded+.more1 {display: none}
     .jumbo-p.expanded {height: auto;}

The jQuery to make it all work:

        $(".non-exp").text(function(index, currentText) {
            return currentText.substr(0, 90) + '...';
        });
        $(document).on('click', '.more1', function(event) {
            event.preventDefault();
            $('.jumbo-p').toggleClass('expanded');
            $('.jumbo-p').removeClass('non-exp');
        });

This puts the limit on the div but that limit is not removed when the class is removed. Please help.

Alex Zahir
  • 949
  • 7
  • 19
  • 50

2 Answers2

2

The problem is that you have replaced the text with "...". You need to undo this change by storing the original text somewhere and showing it again upon clicking the "more" button.

One more thing, I have seen you said that

text-overflow will limit it based on div width. i want to limit it based on character length

You can set the div width based on the number of characters, like this

width: 90ch;

However, there might be some browser compatibility issues. See more at Specify width in *characters*

Community
  • 1
  • 1
Fai
  • 344
  • 5
  • 9
  • that is good but ch as width is still not widely supported and i need to support IE8 and above. But in the future this would be a great method so upvote – Alex Zahir Aug 31 '15 at 05:22
1

Store the original text in a variable and reinsert it on click.

var text = $(".non-exp").text();    
$(".non-exp").text(function(index, currentText) {
        return currentText.substr(0, 90) + '...';
    });
$(document).on('click', '.more1', function(event) {
    event.preventDefault();
    $(".non-exp").text(text);
    $('.jumbo-p').toggleClass('expanded');
    $('.jumbo-p').removeClass('non-exp');
});
mtl
  • 7,529
  • 2
  • 20
  • 22