<p class="lh-copy measure" data-controller="read-more">
  <span data-target="read-more.content">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ut laoreet neque, ut posuere libero. Etiam ut ultrices mi. Donec dictum ultricies justo, vitae molestie nunc finibus ac. Morbi rutrum nunc massa, id eleifend mauris dignissim non. Pellentesque eu turpis mi. Maecenas sed nulla at massa rutrum condimentum. Pellentesque varius mi in libero vulputate, quis cursus purus consequat. Nunc sit amet arcu at nulla interdum volutpat. Nunc ut pellentesque massa. Etiam tempor nulla vel iaculis tempus. Nulla tristique pellentesque viverra.
  </span>
  <button class="hide" data-target="read-more.moreButton" data-action="read-more#showMore">
    Ver más
  </button>
  <button class="hide" data-target="read-more.lessButton" data-action="read-more#showLess">
    Ver menos
  </button>
</p>
.hide {
  display: none;
}

.lh-copy {
  line-height: 1.5;
}

.measure {
  max-width: 30em;
}
class ReadMoreController extends Stimulus.Controller {
  static targets = ["content", "moreButton", "lessButton"]
  lines = 3

  connect() {
    this.content = this.contentTarget.textContent;
    this.showLess()
    if (this.height() > this.expectedHeight()) {
      this.showLess()
    }
  }

  showMore() {
    this.removeContent();
    this.wordsList().forEach((word) => this.addWordToContent(word))
    this.hide(this.moreButtonTarget);
    this.show(this.lessButtonTarget);
  }

  showLess() {
    this.removeContent();
    this.wordsList().forEach((word) => {
      if (this.height() < this.expectedHeight())
        this.addWordToContent(word)
    })

    this.addToContent("...")
    this.hide(this.lessButtonTarget);
    this.show(this.moreButtonTarget);
  }

  show(target) {
    target.classList.remove("hide")
  }

  hide(target) {
    target.classList.add("hide")
  }

  removeContent() {
    this.contentTarget.textContent = "";
  }

  addWordToContent(word) {
    this.addToContent(" " + word);
  }

  addToContent(text) {
    this.contentTarget.textContent += text
  }

  lineHeight() {
    let style = window.getComputedStyle(this.contentTarget)
    return parseFloat(style.lineHeight, 10);
  }

  height() {
    return this.contentTarget.offsetHeight;
  }

  expectedHeight() {
    return this.lines * this.lineHeight();
  }

  wordsList() {
    return this.content.split(" ")
  }
}

const application = Stimulus.Application.start()
application.register('read-more', ReadMoreController)

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

  1. https://unpkg.com/stimulus/dist/stimulus.umd.js