ReadMore/

by yash_mochi

HTML

<!DOCTYPE html>
<html>

  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
  </head>

  <body>
    <div style="display: flex; width: 100%;">
      <div id="div1" class="div-block" style="background-color: #aaa;"></div>
      <div id="div2" class="div-block" style="background-color: #bbb;"></div>
      <div id="div3" class="div-block" style="background-color: #ccc;"></div>
      <div id="div4" class="div-block" style="background-color: #ddd;"></div>
      <div id="div5" class="div-block" style="background-color: #eee;"></div>
    </div>
  </body>

</html>

CSS

.div-block {
  float: left;
  width: 20%;
  padding: 20px;
}
body {
  margin-bottom: 50px;
}

JavaScript

const toggle = (targetId) => {
  const dots = document.getElementById(`dots-${targetId}`);
  const toggle = document.getElementById(`myBtn-${targetId}`);
  const more = document.getElementById(`more-${targetId}`);
  const y = dots.style.display === "none";
  dots.style.display = y ? "inline" : "none";
  toggle.innerHTML = y ? "Read more" : "Read less";
  more.style.display = y ? "none" : "inline";
};
const showParagraph = (targetId, paragraphText, displayLimit) => {
  const pTagElem = document.createElement("p");
  pTagElem.setAttribute("style", "word-break: break-all;");

  if (paragraphText.length > displayLimit) {
    const uniqueId = targetId || "body";
    const dotsSpanElem = document.createElement("span");
    dotsSpanElem.id = `dots-${uniqueId}`;
    dotsSpanElem.textContent = "...";
    dotsSpanElem.setAttribute("style", "display: inline");

    const moreTextSpanElem = document.createElement("span");
    moreTextSpanElem.id = `more-${uniqueId}`;
    moreTextSpanElem.setAttribute("style", "display: none");

    const toggleButtonElem = document.createElement("button");
    toggleButtonElem.id = `myBtn-${targetId}`;
    toggleButtonElem.onclick = () => toggle(targetId);
    toggleButtonElem.innerHTML = "Read more";
    toggleButtonElem.setAttribute(
      "style",
      "background: none !important; border: none; margin: 5px !important; padding: 0 !important; color: #069; text-decoration: underline; cursor: pointer;"
    );

    const firstText = paragraphText.slice(0, displayLimit);
    const secondText = paragraphText.slice(displayLimit);
    moreTextSpanElem.appendChild(document.createTextNode(secondText));

    pTagElem.appendChild(document.createTextNode(firstText));
    pTagElem.appendChild(dotsSpanElem);
    pTagElem.appendChild(moreTextSpanElem);
    pTagElem.appendChild(toggleButtonElem);
  } else {
    pTagElem.appendChild(document.createTextNode(paragraphText));
  }
  document.getElementById(targetId) ?
   ...