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

Customizing the color scheme of specific components using Material UI inline styling

I am currently customizing my TextFields from Material-UI. My background is black and I want both the textField border and text to be white. Here's the relevant part of my code: render() { const styles = { width: { width: '90%& ...

Retrieving time zone using offset with javascript

I am looking for a way to schedule time-based events on my server operating in UTC time. For the user interface, I need to input 2 parameters: The local time when the scheduled event should trigger The timezone offset Instead of displaying timezone n ...

What is the method to turn off readonly property for input fields in Laravel?

I'm encountering an issue with my Laravel project. I have a form with an input field that has the readonly attribute set. <input type="text" name="anamFam" id="anamFam" value="{{$aFam->anam_cont}}" readonly> When I click the edit button, I ...

Creating dropdown options with JSON and Angular

This dilemma has been causing me no end of distress. I am trying to figure out how to populate options for a select tag from a JSON object using Angular. Here is a snippet of the code: <select id="cargo" ng-model="cargo.values.cargoList"> <op ...

Updating an HTML value based on the selected option using JavaScript

I'm working on a form that included a select element: <select class="form-control"> <option>10 pc</option><!--1 USD --> <option>20 pc</option><!--2 USD --> <option>50 pc</option><!--3 USD ...

"PHP Dilemma: Navigating the Ajax Button Press Situation

I've been attempting to create a button that triggers a PHP script on a webpage and updates only a specific div tag, but so far I haven't had any success. Removing the $ajax section of the script allows my buttons to change states, but as soon as ...

What is the best way to retrieve both a response JSON and headers using Got?

Currently, I am utilizing Got for sending requests to a Strapi API from Node.js. The code snippet demonstrates how I achieve this: res.setHeader('Content-Type', 'application/json') try { const request = req.query.request const decod ...

Guide to finding and saving email addresses from a string output: extracting and storing each one individually in a text file

After collecting data from multiple sources, the output I obtained is as follows: "addressId":"132234","businessEntryCount":2026},{"district":"Nordend-West","districtSlug":"frankfurt-am-main- ...

Ways to identify when a specific react component has been clicked

Currently working on developing a klondike game with 4 empty stacks at the start of the game. The initial page layout resembles the first image provided in the link. I am facing an issue where I cannot determine which component was clicked when clicking on ...

Adjust the standard size of the IMG tag using CSS

I have a simple image tag with an incorrect URL http://jsbin.com/monivava/1/edit <img src="http://placekitten!!!.com/g/200/200"> The issue is that the default size for this unsuccessful image is 18x20 (at least in Webkit), but I want it to be 0px ...

Keep sending HTTP requests until the header contains an attachment

Welcome to our web application where you can generate and download a .zip file simply by visiting the URL. I am looking to develop a Node.js application using the requestjs library that will continuously send requests until it detects an attachment header ...

How to verify changes in session variable using PHP and AJAX

Hey there! I'm looking for a way to continually monitor changes in a session variable within PHP. Let's say the session variable "x" starts off with a value of "1" and then, after five seconds, it changes to "2". This session variable "x" is up ...

Concealing the nearest object

I am currently working on using jquery to hide certain content on a website's index page. Within the fiddle, there is commented out code which I have been experimenting with - however, it hides all content divs if any toggle link is clicked. HTML & ...

What are the steps for capturing video using openCV in a python program?

I am facing a challenge in figuring out how to capture a video using openCV. While I have managed to display the video on an html template with the existing codes, I am uncertain about which codes are needed to actually record the video. -camera.py- i ...

Insert JavaScript into this HTML document

I am looking to integrate the "TimeCircles JavaScript library into my project, but I am facing some challenges in doing it correctly. I plan to include the necessary files at the following location: /js/count-down/timecircles.css and /js/count-down/timecir ...

Exploring the integration of angular-ui-select into an angular seed project

I set up a new project using the starter template from https://github.com/angular/angular-seed and now I'm attempting to integrate angular-ui-select for dropdown menus. I've added select.js and select.css files to my index.html as well as install ...

Navigating through React Native with TypeScript can be made easier by using the proper method to pass parameters to the NavigationDialog function

How can I effectively pass the parameters to the NavigationDialog function for flexible usage? I attempted to pass the parameters in my code, but it seems like there might be an issue with the isVisible parameter. import React, { useState } from 'rea ...

Validating Credit Card Numbers with Spaces

Currently, I am in the process of creating a credit card form that requires validation using checkValidity to match the specific card pattern that is dynamically added to the input field. For example, if a user enters a Mastercard number such as 545454545 ...

Updating the columns in a row by clicking the refresh button with ajax in a JSP file

Hey there! I have a table on my JSP page with refresh buttons at the row level. When I click the refresh button, it should check the database and update those two columns with new values. Below is the code snippet for my JSP page: <script src="js/jque ...

SharePoint 2013 on a mobile device does not support scrolling within iframes

Recently, I set up a SharePoint 2013 website with a few iframes. However, when I access the site on my mobile devices (iPad and Android), I am unable to scroll through the entire page by touching within the iframe. I attempted to solve this issue by inclu ...