What is the best way to create a toggle button that can show more or show less of a text snippet with animation?

Is it possible for someone to assist me with showing a long text partially and providing a "show more" button to reveal the rest, along with a "show less" option, all with some CSS animation? I was thinking of using a font awesome arrow down icon for expanding and an arrow up icon for collapsing.

The HTML code snippet:

<div class="qodef-m-content">
    <p class="qodef-m-text">
       Bonjour je suis Olfa une nana hypersensible marié et maman de deux enfants.
       En 2018 je quitte mon activité dans la finance qui ne colle pas avec mes valeurs et je commence une                   formation en naturopathie afin d’avoir des bases en médecines naturelles, très vite ma soif d’apprendre me dirige vers des techniques de massages corps, des thérapies brèves et des soins énergétiques.
 Ce parcours de plusieurs années me permet d’aider plusieurs femmes à se soigner physiquement et mentalement.
2021 je rencontre un soucis de santé qui me contraint à arrêter les massages par avis médical mais ma passion a raison de tout je décide  de me former dans un cursus RNCP sur les différents massages visages pour être Facialiste et en parallèle je passe mon diplôme d’esthéticienne que j’obtiens.
Maintenant je prend plaisir a sublimer vos visages entre mes mains en mettant en pratiquant mon savoir-faire . 
   Je vous donne Rendez-vous m sur Aix en Provence pour découvrir mes soins signatures.
    </p>
</div>

The CSS styling:

.qodef-m-text {
    font-family: "Cormorant Garamond", sans-serif;
    font-style: italic;
    font-weight: 400;
    font-size: 33px;
    line-height: 42px;
    width: 80%;
    margin-left: 10%;
}

Answer №1

There is no need for JavaScript with this solution. CSS can be used to customize the design. The summary tag serves as the visible part, and clicking on it will toggle the visibility of the p element.
An animation has been added for the opening effect.

details p{
  animation: anim 400ms;
  transform-origin: top;
}

@keyframes anim{
 from{
  transform: scale(1, 0);
  opacity: 0;
 }
 to{
  transform: scale(1, 1);
  opacity: 1;
 }
}
<h1>Hello world website</h1>

<details>
  <summary>Show the text</summary>
  <p>Bonjour je suis Olfa une nana hypersensible marié et maman de deux enfants.
       En 2018 je quitte mon activité dans la finance qui ne colle pas avec mes valeurs et je commence une                   formation en naturopathie afin d’avoir des bases en médecines naturelles, très vite ma soif d’apprendre me dirige vers des techniques de massages corps, des thérapies brèves et des soins énergétiques.
 Ce parcours de plusieurs années me permet d’aider plusieurs femmes à se soigner physiquement et mentalement.
2021 je rencontre un soucis de santé qui me contraint à arrêter les massages par avis médical mais ma passion a raison de tout je décide  de me former dans un cursus RNCP sur les différents massages visages pour être Facialiste et en parallèle je passe mon diplôme d’esthéticienne que j’obtiens.
Maintenant je prend plaisir a sublimer vos visages entre mes mains en mettant en pratiquant mon savoir-faire . 
   Je vous donne Rendez-vous m sur Aix en Provence pour découvrir mes soins signatures.
</p>
</details>

Answer №2

To start, ensure that you have integrated the Font Awesome library into your HTML file. You can insert the provided link in the head section of your HTML code:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
        
<div class="qodef-m-content">
      <p class="qodef-m-text long-text">
        <!-- Enter your lengthy text content here -->
      </p>
      <button class="show-more-btn"><i class="fas fa-chevron-down"></i>Show More</button>
    </div>
    
    <style>
      .qodef-m-text {
        /* Your current CSS styles */
        height: 200px; /* Specify a fixed height for initial display */
        overflow: hidden; /* Conceal overflowing content */
        transition: height 0.3s ease; /* Implement smooth animation for height changes */
      }
    
      .qodef-m-content.collapsed .qodef-m-text {
        height: auto; /* Expand the height to reveal full content */
      }
    
      .show-more-btn {
        /* Styling for your button */
        display: block;
        margin-top: 10px;
        background: none;
        border: none;
        cursor: pointer;
      }
    </style>
    
    <script>
      const textContainer = document.querySelector('.qodef-m-text');
      const showMoreBtn = document.querySelector('.show-more-btn');
      const collapsedClass = 'collapsed';
    
      showMoreBtn.addEventListener('click', function() {
        textContainer.classList.toggle(collapsedClass);
        if (textContainer.classList.contains(collapsedClass)) {
          showMoreBtn.innerHTML = '<i class="fas fa-chevron-down"></i> Show More';
        } else {
          showMoreBtn.innerHTML = '<i class="fas fa-chevron-up"></i> Show Less';
        }
      });
    </script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is the button failing to direct you to the intended destination?

I'm facing an issue with a button tied to a JavaScript function using onClick(); My interface allows me to ban players on a game server, but when I select anyone here: https://i.stack.imgur.com/kcE1t.png, it always selects wartog for some reason. In ...

Image not showing up on HTML page following navigation integration

Having trouble with my responsive website setup - the background image for ".hero-image" isn't showing up after adding the navigation. Google Chrome console is throwing a "Failed to load resource: the server responded with a status of 404 (Not Found)" ...

Unable to establish an external connection with the node

Currently, I am in the process of establishing a connection to a local server and running an app on port 8080 using node. Both node and apache are installed on my system. When Apache is active, I can access the server externally. However, when Node is runn ...

What could be causing my form to malfunction when attempting to submit data using Ajax and an external PHP script that is handling two string inputs?

Hello, I am facing an issue while trying to utilize Ajax to interact with a PHP file and submit both inputs (fullname and phonenumber). When I click the submit button, it simply refreshes the page without performing the desired action. Below is the code I ...

Tips for assigning a default value when an error occurs

Currently diving into the world of React and experimenting with rendering 10 pieces of data from a specific API. After crafting a function to iterate through the fetched information, extracting the title and image has been quite the challenge: for (let ...

Activate when every single pixel within an element is see-through

I've designed a web page that includes two canvas elements stacked on top of each other. The purpose of this setup is to allow me to "erase" the top canvas and reveal an image loaded into the bottom canvas. So far, this functionality has been working ...

Encountering difficulties in JavaScript while trying to instantiate Vue Router

After following the guide, I reached the point where creating a Vue instance was necessary (which seemed to work). However, it also required providing a Vue Router instance into the Vue constructor, as shown below. const router = new VueRouter({ routes }) ...

Adjust the size of the div based on a percentage of the header div

I'm looking to add a new div within the header of my WordPress site. I want this div to be a percentage of the parent div's size, specifically occupying only the right side of the header. Right now, the header contains my logo on the left side, a ...

What techniques are most effective for creating unit tests in a Node.js environment?

One of the challenges I am facing is writing a unit test for a module where I load a mustache template file. To tackle this, I am exploring the use of mocha, chai, and rewire. Below is an excerpt from my module.js: var winston = require('winston&apo ...

Updating the DOM with an EventListener in Angular 5 is not functioning properly

Situation : Utilizing an Angular PWA for communication with an iOS native app via WKWebview. Implementing messageHandlers to facilitate data sharing between TypeScript and Swift logic code. Issue : Employing addEventListener to monitor a specific event on ...

Tips for Angular JS Single Page Applications: Implementing Angular Controllers to Invoke Angular Services

Currently, I'm in the process of building a Node.js Application using Angular.js and Express.js. My goal right now is to populate a list with customer names and addresses by using this code snippet: var mylist = new generic.list(); mylist.add({name ...

Receiving an error stating that .startsWith() is not a function in react native

I'm having trouble searching for items using a search bar. The original items are in 'prod', but I keep encountering errors such as 'startsWith() is not a function' and sometimes '.toLowerCase() is not a function'. const ...

"I'm trying to figure out the best way to use Selenium and Python to send a character sequence to a contenteditable element that has its attribute set

Recently, I've been experimenting with using Python 3.6 and Selenium to automate a simple task - logging into a chat website and sending messages automatically. is the webpage where I want to send the messages. Despite my limited experience with Py ...

JavaScript code must be tailored to reference a JS file based on the specific environment, whether it be Production, Development, or staging

I need to determine which .js file to refer based on the URL of Prod, Dev, and QA environments. For Production URLs (domain.com and www.domain.com), I should refer to prod.js file. For Dev and QA URLs (dev.domain.com and staging.com), I should refer to s ...

Using AngularJS to add a unique custom class directive to each item in an ng-repeat loop

Can anyone help me figure out why the width of a div isn't being set dynamically using AngularJS? <ul id="contents"> <li ng-repeat="content in contents"> <div class="content_right custom_width"> <div class="title"> ...

loading a module's dependencies seamlessly with RequireJS

Currently, I am working with Knockout and Require in my project. I have isolated some Knockout handlers into a separate module that I want to utilize. While there is no specific JavaScript code relying on this module, it is referenced in the data-bind attr ...

Utilizing jQuery to display labels only for selected checkboxes while concealing the ones that are not checked

I currently have the following setup: <style>.selectit{display:none;}</style> <div id="foo"> <label class="selectit"> <input type="checkbox" name="one" id="one" checked> One </label> <label class="selectit"> <i ...

Tips for handling a multi-step form in React?

Below is the code snippet for the multistep form I have been working on: import clsx from 'clsx'; import React from 'react'; import PropTypes from 'prop-types'; import { makeStyles, withStyles } from '@material-ui/styles ...

Resolving issues with JavaScript caused by Polymer updates

I am a novice when it comes to working with Polymer. From what I have gathered, there seems to be compatibility issues with Mozilla and Safari. After researching on StackOverflow, I found that adding addEventListener('WebComponentsReady', funct ...

Divs that overlap and share the same font may exhibit variations in letter spacing

In my design, I have a div that overlays another div with the exact same offsets and font properties. The upper div has a transparent background and typically covers the text of the underlying div. However, I recently noticed an issue with my script where ...