Home > OS >  Show more text if there is too much text
Show more text if there is too much text

Time:11-07

I am using this module to implement "Show more/Show less". Can you tell me how to make the "Show more" link displayed only if the height is greater than a certain number (for example, the same 42 pixels), and not always? Otherwise, even with one line, this link is displayed, although this is obviously not necessary.

html

    <div >
            <div >
              <div >
                <div id="summary">
                  <p  id="collapseSummary">
                    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc porttitor maximus laoreet. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. In hac habitasse platea dictumst. Suspendisse venenatis sollicitudin erat in gravida. Sed eget nisl tristique, commodo lectus sit amet, vulputate sem. Cras porttitor lorem ipsum, sit amet iaculis massa feugiat vitae. Curabitur sapien odio, ullamcorper tincidunt interdum vitae, vestibulum eu neque. Nam leo massa, fringilla eget mauris feugiat, auctor suscipit justo.
                  </p>
                  <a  data-toggle="collapse" href="#collapseSummary" aria-expanded="false" aria-controls="collapseSummary"></a>
                </div></div></div>

css

    #summary {
    font-size: 14px;
      line-height: 1.5;
    }
    
    #summary p.collapse:not(.show) {
        height: 42px !important;
        overflow: hidden;
      
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;  
    }
    
    #summary p.collapsing {
        min-height: 42px !important;
    }
    
    #summary a.collapsed:after  {
        content: '  Read More';
    }
    
    #summary a:not(.collapsed):after {
        content: '- Read Less';
    }

https://codepen.io/joserick/pen/ooVPwR

CodePudding user response:

You can use scrollHeight to get the content's height inside the element, even when some of it is hidden.

The Element.scrollHeight read-only property is a measurement of the height of an element's content, including content not visible on the screen due to overflow.

MSDN Article

CSS


a.collapsed {
  display: none;
}

JavaScript


const height = document.querySelector("#collapseSummary").scrollHeight;
if (height > 100) {
   const showMoreLink = document.querySelector(".collapsed");
   showMoreLink.style.display = "block";
}
  • Related