SamSmith SamSmith -4 years ago 105
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

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">
$text = $page->Article_Text;

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{
$("body").on("click", ".read-more-link", function(event){
$(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){
$(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>");

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


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

Answer Source

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:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download