JSFiddle - React, Tailwind, and code Playground
by Ashish
HTML
<div class="text-container">
<h1>Head 1</h1>
<div class="text-content short-text">
This text is revealed by button 1 and hidden by button 3.
This text is revealed by button 1 and hidden by button 3.
This text is revealed by button 1 and hidden by button 3.
This text is revealed by button 1 and hidden by button 3.
</div>
<div class="show-more">
<a href="#">Show more</a>
</div>
</div>
<div class="text-container">
<h1>Head 2</h1>
<div class="text-content short-text">
This text is revealed by button 1 and hidden by button 3.
This text is revealed by button 1 and hidden by button 3.
This text is revealed by button 1 and hidden by button 3.
This text is revealed by button 1 and hidden by button 3.
This text is revealed by button 1 and hidden by button 3.
</div>
<div class="show-more">
<a href="#">Show more</a>
</div>
</div>
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;
}
JavaScript
$(".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;
console.log(actualHide);
console.log(visibleHeight);
if (actualHide > visibleHeight) {
$link.show();
} else {
$link.hide();
}
});
$(".show-more a").on("click", function() {
var $link = $(this);
var $content = $link.parent().prev("div.text-content");
var linkText = $link.text();
$content.toggleClass("short-text, full-text");
$link.text(getShowLinkText(linkText));
return false;
});
function getShowLinkText(currentText) {
var newText = '';
if (currentText.toUpperCase() === "SHOW MORE") {
newText = "Show less";
} else {
newText = "Show more";
}
return newText;
}