Insert ellipsis after specific number of lines

I am trying to display only the first 5 lines of text. The problem is that the way the text is set up is multiple <p> tags within a div, such as

<div class="myText">
  <p>some text</p>
  <p>some text</p>
  <p>some text</p>
  <p>some text</p>
  <p>some text</p>
  <p>some text</p>
  <p>some text</p>
</div>

I have looked at many answers on this site such as this one, and this one and in other places, such as http://codepen.io/martinwolf/pen/qlFdp, and https://css-tricks.com/line-clampin/, but none of them work for this case, where I would want the ellipsis after the last word on the last line even if it does not reach the end of the line, and there are multiple <p> tags.

I am using JavaScript with Angular.

Answers:

Answer

Yes, you could use some plug-in, but this logic is not incredibly hard to write yourself. The basic notion is to keep reducing the amount of text until it fits. This sounds expensive, but in practice it works fine, and could be optimized if necessary.

// Populate an element with text so as to fit into height
function truncate(elt, content, height) {

  function getHeight(elt) { return elt.getBoundingClientRect().height; }
  function shorten(str)   { return str.slice(0, -1); }

  elt.style.height = "auto";
  elt.textContent = content;

  // Shorten the string until it fits vertically.
  while (getHeight(elt) > height && content) {
    elt.textContent = (content = shorten(content)) + '...';
  }

}

To use this:

truncate(div, "Some very long text to be truncated", 200)

To use with HTML content, adapt/extend as necessary.

Answer

Try jQuery dotdotdot plugin. URL: http://dotdotdot.frebsite.nl/

I have made a sample of the code in jsFiddle Link

Here's the code:

$(document).ready(function() {
	$(".myText").dotdotdot();
});
p {
    margin:0;
    padding:0;
    font:12px/15px Verdana, Geneva, Tahoma, Arial, Helvetica, sans-serif;
}
.myText {
    height:75px; /*  this needs to be the height of 5 lines of text. Here it is 15px (line-height of one line) * 5 = 75px */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jQuery.dotdotdot/1.7.2/jquery.dotdotdot.min.js"></script>

<div class="myText">
  <p>some text</p>
  <p>some text</p>
  <p>some text</p>
  <p>some text</p>
  <p>some text</p>
  <p>some text</p>
  <p>some text</p>
</div>

Hope this helps.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.