Since your sample code did not work fully, I decided to refine one of my own samples that I created in a post some time ago.
DEMO - Show more / less and hide the link if necessary
The demonstration shows that the first text has no link, and the second for the link. If you add a few more characters to the first text, you will see that the link appears when you re-run the script.
The idea is to double check the client against the actual height and determine if you want to display the link. As shown below.
$(".show-more a").each(function() { var $link = $(this); var $content = $link.parent().prev("div.text-content"); console.log($link); var visibleHeight = $content[0].clientHeight; var actualHide = $content[0].scrollHeight - 1;
The demo uses the following HTML:
<div class="text-container"> <h1>Lorem ipsum dolor</h1> <div class="text-content short-text"> Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt </div> <div class="show-more"> <a href="#">Show more</a> </div> </div> <div class="text-container"> <h1>Lorem ipsum dolor</h1> <div class="text-content short-text"> Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. </div> <div class="show-more"> <a href="#">Show more</a> </div> </div>โ
and the following basic CSS:
div.text-container { margin: 0 auto; width: 75%; } .text-content{ line-height: 1em; } .short-text { overflow: hidden; height: 2em; } .full-text{ height: auto; } h1 { font-size: 24px; } .show-more { padding: 10px 0; text-align: center; }
source share