Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert read more button when line clamping

I would like a read more button to appear when text overflows and to not show if the text doesn't overflow

So far I have the following code to line clamp if it overflows to line 18:

display: -webkit-box;
-webkit-line-clamp: 18;
-webkit-box-orient: vertical;  
overflow: hidden;

I've had a thorough search and can only find solutions that toggle show more, show less when a div exceeds a certain length.

However, I would only like the button to show if it exceeds the length: <a href="article.html">Read more</a>

like image 621
Tÿler Avatar asked Aug 09 '18 17:08

Tÿler


2 Answers

You could use javascript to achieve this by checking if the element has an overflow and toggle the button based on whether or not the element has an overflow.

function showReadMoreButton(element){
   if (element.offsetHeight < element.scrollHeight ||
        element.offsetWidth < element.scrollWidth) {
        // your element has an overflow
        // show read more button
    } else {
        // your element doesn't have overflow
    }
}

Example call:
var elementToCheck = document.getElementById('someElementToCheck');
showReadMoreButton(elementToCheck);


// call showReadMoreButton() after page load and/or window resize and/or functions which change content within the overflow element.

Note that you would need to call this function from the appropriate sections that could change content within the overflow element.

Reference for overflow check from: Check with jquery if div has overflowing elements

like image 77
Jako Basson Avatar answered Sep 22 '22 02:09

Jako Basson


To solve this i used the following javascript:

var element = document.querySelector('.pcontent');
if( (element.offsetHeight < element.scrollHeight) || (element.offsetWidth < element.scrollWidth)){
   // your element have overflow
  document.querySelector('#read-more').style.visibility = "visible";
}
else{
  //your element don't have overflow

With these elements:

<p class="pcontent">Text here</p>
<a id="read-more" href="readmore.html">Read more</a>

And this css:

.pcontent {
    display: -webkit-box;
    -webkit-line-clamp: 18;
    -webkit-box-orient: vertical;  
    overflow: hidden;
}
#read-more {
    visibility: hidden;
}
like image 42
Tÿler Avatar answered Sep 23 '22 02:09

Tÿler