inquisitivemongoose
inquisitivemongoose

Reputation: 386

Show "read more" button after specific number of lines with JS

I want to make my paragraphs 3 lines long at most. If it goes beyond that, I show a "read more" button.

enter image description here

The "read more" button should be hidden for the first post.

I know how to limit the paragraphs using CSS, but I'm having trouble with showing/hiding the "read more" button.

// CSS code to limit paragraphs to 3 lines: 

.post-p {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3; /* number of lines to show */
  -webkit-box-orient: vertical;
  line-height: 16px; /* fallback */
  max-height: 48px; /* fallback */
}

I am trying to use jQuery's .height() function to access the paragraph's height, but it always prints '16', which I assume is the line-height that I set in the CSS code above. Is there another way to check a paragraph's height or number of lines?

Additional note: I am using EJS to send in an array of post objects from my app.js file.

<% posts.forEach(function(post) { %>
  <div>
    <p class="post-p"><%= post.content %></p>
    <a class="read-more-btn" href="/posts/<%=post._id%>">Read More...</a>
    <script type="text/javascript">
      console.log($('.post-p').height());
    </script>
  </div>
<% }); %>

// Extra note: I removed the h1 tag from the image I linked to simplify the code.

Upvotes: 3

Views: 5454

Answers (2)

inquisitivemongoose
inquisitivemongoose

Reputation: 386

Edit: Got it working thanks to @Alexander van Oostenrijk. Here's my solution below.

<% posts.forEach(function(post) { %>
  <div class="post-div">
    <h1><a href="/posts/<%=post._id%>"><%= post.title %></a></h1>
    <p class="post-p"><%= post.content %></p>
    <a class="read-more-btn" href="/posts/<%=post._id%>">Read More...</a>
  </div>
<% }); %>

<script type="text/javascript">
  $('.post-div').each(function(i, obj) {
    if (obj.children[1].clientHeight < 48) { // post-p
      $(obj.children[2]).hide(); // read-more-btn
    }
  });
</script>

Upvotes: 0

Alexander van Oostenrijk
Alexander van Oostenrijk

Reputation: 4764

Please be aware that line-clamp doesn't have great support across browsers yet (see https://caniuse.com/?search=line-clamp). You may be better off creating the ellipsis yourself.

You can obtain the height in pixels of an element using this:

var clientHeight = document.getElementById('my-element').clientHeight;

Upvotes: 2

Related Questions