Yujun Wu
Yujun Wu

Reputation: 3012

use jQuery to expand/collapse text

I want to cut off text based on a fixed height.When the text is cut off, a "more" link is used to expand to text. When the text is expanded, a "less" link is used to collapse the text. I wrote the js as this:

$(document).ready(function () {
      // line height in 'px'
      var maxheight=218;
      var showText = "More";
      var hideText = "Less";

      $('.textContainer_Truncate').each(function () {
        var text = $(this);
        if (text.height() > maxheight){
            text.css({ 'overflow': 'hidden','height': maxheight + 'px' });

            var link = $('<a href="#">' + showText + '</a>');
            var linkDiv = $('<div></div>');
            linkDiv.append(link);
            $(this).after(linkDiv);

            link.click(function (event) {
              event.preventDefault();

              if (text.css('height') == 'auto') {
                  $(this).html(showText);
                  text.css('height', maxheight + 'px');
              } else {
                  $(this).html(hideText);
                  text.css('height', 'auto');
              }
            });
        }       
      });
  });

The html code is:

<div class="textContainer_Truncate">
  <p>content</p>
</div>

My problem is that the "more" link works but the "less" doesn't. That is, when more is clicked, the text is expanded but it won't go back when the less is clicked.What's wrong here? Thanks

Upvotes: 4

Views: 15609

Answers (2)

Rafee
Rafee

Reputation: 4078

I believe you are looking this one

http://jsfiddle.net/rbUst/

$(".act").click(function() {
  var val = $(this).text();
  if (val == "More") {
    $("div").css('height', '200px');
    $(this).text("less");
  } else {
    $("div").css('height', '20');
    $(this).text("More");
  }
  return false;
});
div {
  background-color: #CCA;
  height: 20px;
  overflow: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<a href="" class="act">More</a> 
<div>This fskdljfl sflsdajfsadf
  <br />fsdafsdfsadfsdf dfjsadf slfkjsf</div>

above is the live example..

Upvotes: 0

adeneo
adeneo

Reputation: 318232

It's just a small error, this:

if (text.css('height') == 'auto') {

should be this:

if (text.height() > maxheight) {

FIDDLE

Upvotes: 5

Related Questions