SamSmith SamSmith - 3 months ago 8
HTML Question

Text not hiding on click

I have six boxes that each contain one paragraph each with different content. There is a character limit set to 200 characters. After 200 characters, the remaining content (if any) is hidden until the user clicks the

Show More
link.

When the user clicks the
Show Less
link the text show go back to the character limit. However, that is not the case; when the user clicks the
Show More
link all content is shown, but when the user clicks the
Show Less
link the content does not contract.

I saw other SO posts about show and hiding content, but after implementing their answers in effort to solve my issue, I am still lost. This is one of my first times implementing jQuery so please excuse my confusion at such an elementary level.

Any suggestions as to why the
Show Less
does not contract the content are appreciated.

<div class="col-md-8" id="article">
<?php
$text = $page->Article_Text;
?>

<script>
$(document).ready(function(){
var readMoreHTML = $(".read-more").html();
var lessText = readMoreHTML.substr(0, 200);

if(readMoreHTML.length > 200){
$(".read-more").html(lessText).append("<a href=''class='read-more-link' style='color:gray; text-decoration:none'>Show More</a>");
} else{
$(".read-more").html(readMoreHTML);
}
$("body").on("click", ".read-more-link", function(event){
event.preventDefault();
$(this).parent(".read-more").html(readMoreHTML).append("<a href=''class='show-less-link' style='color:gray; text-decoration:none'>Show Less</a>");
});
$("body").on("click", ".show-less-link", function(event){
event.preventDefault();
$(this).parent(".read-more").html(readMoreHTML.subtr(0,200)).append("<a href=''class='read-more-link' style='color:gray; text-decoration:none'>Show More</a>");
});
});
</script>


<div class="content">
<div class="read-more">
<?php echo $text ?>
</div>
</div>

</div><!--#article-->


(Please excuse the inline CSS as it is only for testing purposes).

Answer

In the last part of your JS, just use your lessText variable and it will work. The jQuery .html() method can't accept readMoreHTML.subtr(0,200) as an input.

$(this).parent(".read-more").html(lessText).append("<a href=''class='read-more-link' style='color:gray; text-decoration:none'>Show More</a>");

Working codepen: http://codepen.io/staypuftman/pen/akZdzg