Use jQuery to expand / smooth text

I want to cut text based on a fixed height. When the text is disabled, the "more" link is used to expand the text. When the text expands, a less link is used to smooth the text. I wrote js like 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'); } }); } }); }); 

Html code:

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

My problem is that the more link works, but the less link does not. That is, when more is pressed, the text expands, but it does not return when less is pressed. What is wrong here? Thanks

+4
source share
2 answers

This is a small mistake:

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

should be as follows:

 if (text.height() > maxheight) { 

Fiddle

+4
source

I believe that you look at it

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 a living example.

0
source

All Articles