Home > OS >  How can I achieve show more text just like youtube?
How can I achieve show more text just like youtube?

Time:10-30

Here is an example of YouTube that what I want to achieve:
https://www.youtube.com/watch?v=0PKFQciUWBU&ab_channel=Lesics enter image description here

As the image above, if the text is more than three lines, it will fold the text and show the show more button.

I only found to use the -webkit-line-clamp to achieve this.

Whereas, there are several problems:
1.When the text is more than three lines, then show the Show more button, but how can I get to know whether the text is more or less than three lines?

2.-webkit-line-clamp is only works for webkit browser, how can I compile with any other browser(such as firefox).

Thank you.

CodePudding user response:

You could do something like this:

for (const el of document.getElementsByClassName('shorten')) {
  const text = el.textContent;
  const summary = text.substring(0, 70)   '... ';
  el.textContent = summary;
  
  const showmore = document.createElement('span');
  showmore.textContent = 'Show more';
  showmore.style.fontWeight = 'bold';
  showmore.addEventListener('click', () => el.textContent = text);
  el.appendChild(showmore);
}
/* just for demostration purposes. not actually needed */

.box {
  width: 200px;
  height: 100px;
  background-color: lightgray;
  overflow: auto;
  margin: 10px;
  display: inline-block;
}
<div >
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse ac elementum nunc. Cras vehicula, ante nec iaculis semper, mi justo ornare ipsum, ac sollicitudin tortor tellus at magna. In augue.
</div>

<div >
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse ac elementum nunc. Cras vehicula, ante nec iaculis semper, mi justo ornare ipsum, ac sollicitudin tortor tellus at magna. In augue.
</div>

<div >
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse ac elementum nunc. Cras vehicula, ante nec iaculis semper, mi justo ornare ipsum, ac sollicitudin tortor tellus at magna. In augue.
</div>

This JavaScript code loops over every element with the class shorten, truncates each element to 70 characters, adds ellipses, and a button to show more text.

I also added some CSS code to demonstrate how this might work inside a UI box, however, this is not needed for the JavaScript to work.

Note: Your question asks to truncate the string to a maximum of three lines, however, it is very hard to calculate the effective number of lines shown. To make it simpler, it is better to just truncate to a certain number of characters. If you want to get really fancy, you might be able to change the number of characters truncated to for each element/class name, but that is out of the scope of this question.

  • Related