TailwindCSS read more/less with transition using line-clamp truncate in JS and ReactJS

Updated by shortbuzz

flower with cards

The multi-line truncation with line-clamp utility class from Tailwind CSS will be used to demonstrate how to create a show/hide feature with a transition effect in both pure JavaScript and ReactJS in this post.

Creating a Read More/Read Less Button using Tailwind CSS and Javascript

HTML with TailwindCSS
Using tailwind truncate multiple lines we will apply the show more/less feature

The Tailwind Multiline truncate plugin must be installed before you can proceed.The official line-clamp documentation can be found here.

<p class="line-clamp-5 transition duration-300 paragraph ">
In this article, we'll demonstrate how to create a "Read More Read Less" button using HTML and CSS. 
When you want to hide more details while still giving readers a sense of what the article or post is about, 
the read more and read less buttons might be useful.</p>

JAVASCRIPT
Here is the JavaScript code to determine whether an element has been truncated.

function showMoreLess() {
    var elements = document.querySelectorAll('.paragraph');
    elements.forEach(function(element) {
        if (element.scrollHeight > element.clientHeight) {
            var button = document.createElement("button");
            button.type = "button";
            button.classList.add("showMoreLess");
            button.textContent = "read more";
            element.parentNode.insertBefore(button, element.nextSibling);
        }
    });
    var showMoreLessButtons = document.querySelectorAll(".showMoreLess");
    showMoreLessButtons.forEach(function(button) {
        button.addEventListener("click", function() {
            var paragraph = button.previousElementSibling;
            if (paragraph.classList.contains("line-clamp-none")) {
                button.textContent = "read more";
                paragraph.classList.remove("line-clamp-none");
            } else {
                button.textContent = "read less";
                paragraph.classList.add("line-clamp-none");
            }
        });
    });
}
showMoreLess();

Using offsetHeight and scrollHeight, determine whether a text has been shortened.
OffsetHeight and scrollHeight are two characteristics for HTML elements that we can use to determine whether the text has been truncated.

offsetHeight:

is a measure of the element's height in pixels, which includes any borders, padding, and horizontal scrollbars (if rendered).

scrollHeight:

JavaScript has a property called "scrollHeight" that calculates an element's overall height, including any content that is hidden because of overflow.

offsetHeight and scrollHeight calculation in javascript for hide/show -read more/less text

Tailwindcss show/hide transition reactjs

Reactjs

import React, { useEffect } from "react";

const ShowMoreLess = () => {
  useEffect(() => {
    const elements = document.querySelectorAll(".paragraph");
    elements.forEach((element) => {
      if (element.scrollHeight > element.clientHeight) {
        const button = document.createElement("button");
        button.type = "button";
        button.classList.add("showMoreLess");
        button.textContent = "read more";
        element.parentNode.insertBefore(button, element.nextSibling);
      }
    });
    const showMoreLessButtons = document.querySelectorAll(".showMoreLess");
    showMoreLessButtons.forEach((button) => {
      button.addEventListener("click", () => {
        const paragraph = button.previousElementSibling;
        if (paragraph.classList.contains("line-clamp-none")) {
          button.textContent = "read more";
          paragraph.classList.remove("line-clamp-none");
        } else {
          button.textContent = "read less";
          paragraph.classList.add("line-clamp-none");
        }
      });
    });
  }, []);

  return (
    <p className="line-clamp-5 transition duration-300 paragraph">
      In this article, we'll demonstrate how to create a "Read More Read Less"
      button using HTML and CSS. When you want to hide more details while still
      giving readers a sense of what the article or post is about, the read
      more and read less buttons might be useful.
    </p>
  );
};

export default ShowMoreLess;

This code gives texts the "read more/read less" feature. Usingdocument. querySelectorAll(), it first chooses all elements with the class 'paragraph'. A "read more" button is added after the element if the content's height is greater than the element's visible height.

The code checks whether the previous sibling element has the class "line-clamp-none" when the button is clicked. If so, the button's name changed to "read more" and the paragraph's class of "line-clamp-none" is removed. If the "line-clamp-none" class is unavailable, the button name is changed to "read less" and the class is added to the paragraph.

More articles from shortbuzz

ecommece template tailwindcss text and businessman
Technology

Get Free TailwindCSS eCommerce Template: Build Online Store

TailwindCSS eCommerce template free: Take advantage of our template & boost your online store's sales with a visually stunning and user-friendly website design continue reading

OpenAI logo chatgpt
Technology

How to block ChatGPT from access the content of your website

By adding code to robots.txt, .htaccess or Nginx server, you can stop ChatGPT from access or crawl your website content that is being used for AI training data continue reading

Google sign-in button and Google logo
Technology

How to migrate from Google Sign-In API to Identity Services

Use Google Identity Services API to improve the user experience & security of your website. Replace old Google Sign-In API with new method: Full migration guide continue reading

Convert Number to Words
Technology

Convert Number to Words using Javascript, Jquery, ReactJS

Code and output for Convert number to words using JQuery, ReactJS, JavaScript, and TypeScript. Example: convert 1 to one continue reading

cloud server with laptop
Technology

Best web hosting service provider in Saudi Arabia (KSA)

Find the best web hosting service providers for your company in Saudi Arabia. Our detailed list includes the most cost-effective, reliable, and fast options. continue reading

Web hosting server and cloud hosting server
Technology

What is Web Hosting and Types: A Complete Beginners Guide

For creation of websites requires web hosting. Learn about many types and their advantages and disadvantages to select the best option for your website. continue reading

Using tailwind css align item in the centre of the screen text and tailwind logo
Technology

Tailwind CSS center div vertically and horizontally

Using tailwindCSS, place the div in the middle of the screen, both vertically and horizontally, using flexbox or grid system with simple explanation. continue reading

Xampp error windows
Technology

How to fix Error: MySQL shutdown unexpectedly in XAMPP

The cause of "Error: MySQL Shutdown Unexpectedly" in XAMPP, shutting down MySQL without running XAMPP as an administrator frequently leads to corruption. continue reading

Bootstrap icon and Tailwind css icon and grid layout design
Technology

How to make Tailwind CSS grid system like Bootstrap grids

Tailwind offers grid-template-column utility for creating basic grids, as well as the grid-cols-{size} & col-span-{size} utilities to create bootstrap-like grid continue reading

Python logo with folder icon and python code on computer screen in the background
Technology

Python Check If File Exists - Python Check If Directory Exists?

path.exists(path) method in python is used to check if a given file or directory exists or not; if it exists, it returns true or else return False continue reading