What is the best way to implement a smooth transition effect like fade animation when toggling between display none and display block

I have successfully implemented a JavaScript code to toggle the visibility of text on button click, but now the client wants to include animations for appearing and disappearing text. I am unsure whether to apply a fade effect or a slide effect to meet the client's requirements. Can someone guide me on how to achieve this?

    function ReadmoreFunction() {
      var dots = document.getElementById("dots");
      var moreText = document.getElementById("more-text");
      var btnText = document.getElementById("readMoreBtn");
    
      if (dots.style.display === "none") {
        dots.style.display = "inline";
        btnText.innerHTML = "Read more";
        moreText.style.display = "none";
      } else {
        dots.style.display = "none";
        btnText.innerHTML = "Read less";
        moreText.style.display = "inline";
      }
    }
#more-text{
  display: none;
  transition: 2s;
}
#readMoreBtn{
background: #ff963b;
color: #fff;
border:1px solid #ff963b;
border-radius: 5px;
padding: 7px 5px;
}
    <div class="category-description std">
        <h2 style="text-align:=justify;"><strong>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</strong></h2>
    
        <p style="text-align:=justify;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur efficitur sodales erat luctus blandit. Vestibulum rutrum tellus fermentum massa pharetra maximus. Morbi sit amet metus vel massa tempus iaculis. Ut sit amet ligula dolor. Nam a sem at est sagittis volutpat. Vestibulum dapibus et orci eu placerat. Suspendisse placerat quis elit sed fringilla. Praesent finibus vestibulum augue in auctor. Etiam interdum dolor mi, ut facilisis magna malesuada ut. Fusce sed eros nibh.</p><span id="dots"></span>
    <span id="more-text">
        <h2 style="text-align:=justify;"><strong>**Get best quality art and craft supplies within your budget**</strong></h2>
    
        <p style="text-align:=justify;">Integer hendrerit suscipit quam ultrices tristique. Integer vel tortor vel risus ultrices tempus tempor a mauris. Etiam venenatis, elit non aliquam sollicitudin, diam tellus dictum lacus, ac scelerisque metus purus nec quam. Donec elementum vitae erat sed condimentum. Aliquam at lorem mollis, porttitor dui at, finibus magna. Aliquam id efficitur lectus, eu ultricies nibh. Nam et posuere mauris, eget hendrerit nisi. Curabitur non tortor enim.</p>
        
        <h2 style="text-align:=justify;"><strong>Lorem ipsum dolor sit amet, consectetur adipiscing elit. </strong></h2>
    
        <p style="text-align:=justify;">Integer hendrerit suscipit quam ultrices tristique. Integer vel tortor vel risus ultrices tempus tempor a mauris. Etiam venenatis, elit non aliquam sollicitudin, diam tellus dictum lacus, ac scelerisque metus purus nec quam. Donec elementum vitae erat sed condimentum. Aliquam at lorem mollis, porttitor dui at, finibus magna. Aliquam id efficitur lectus, eu ultricies nibh. Nam et posuere mauris, eget hendrerit nisi. Curabitur non tortor enim.</p></span>
    </div>
    <center><button onclick="ReadmoreFunction()" id="readMoreBtn">Read more</button></center>

Answer №1

Hey there! I've updated your code to utilize font-size instead of display in order to implement a transition effect

function AdjustTextSize() {
  var dots = document.getElementById("dots");
  var moreText = document.getElementById("more-text");
  var btnText = document.getElementById("readMoreBtn");

  if (dots.style.display === "none") {
    dots.style.display = "inline";
    btnText.innerHTML = "Read more";
    moreText.style.fontSize = "0";
  } else {
    dots.style.display = "none";
    btnText.innerHTML = "Read less";
    moreText.style.fontSize = "initial";
  }
}
#more-text{
  font-size: 0;
  transition: 1s font-size;
}
#readMoreBtn {
  background: #ff963b;
  color: #fff;
  border:1px solid #ff963b;
  border-radius: 5px;
  padding: 7px 5px;
}
<div class="category-description std">
  <h2 style="text-align:=justify;"><strong>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</strong></h2>
  
  <p style="text-align:=justify;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur efficitur sodales erat luctus blandit. Vestibulum rutrum tellus fermentum massa pharetra maximus. Morbi sit amet metus vel massa tempus iaculis. Ut sit amet ligula dolor. Nam a sem at est sagittis volutpat. Vestibulum dapibus et orci eu placerat. Suspendisse placerat quis elit sed fringilla. Praesent finibus vestibulum augue in auctor. Etiam interdum dolor mi, ut facilisis magna malesuada ut. Fusce sed eros nibh.</p><span id="dots"></span>
  <span id="more-text">
    <h2 style="text-align:=justify;"><strong>**Get best quality art and craft supplies within your budget**</strong></h2>
    
    <p style="text-align:=justify;">Integer hendrerit suscipit quam ultrices tristique. Integer vel tortor vel risus ultrices tempus tempor a mauris. Etiam venenatis, elit non aliquam sollicitudin, diam tellus dictum lacus, ac scelerisque metus purus nec quam. Donec elementum vitae erat sed condimentum. Aliquam at lorem mollis, porttitor dui at, finibus magna. Aliquam id efficitur lectus, eu ultricies nibh. Nam et posuere mauris, eget hendrerit nisi. Curabitur non tortor enim.</p>
        
    <h2 style="text-align:=justify;"><strong>Lorem ipsum dolor sit amet, consectetur adipiscing elit. </strong></h2>
    
    <p style="text-align:=justify;">Integer hendrerit suscipit quam ultrices tristique. Integer vel tortor vel risus ultrices tempus tempor a mauris. Etiam venenatis, elit non aliquam sollicitudin, diam tellus dictum lacus, ac scelerisque metus purus nec quam. Donec elementum vitae erat sed condimentum. Aliquam at lorem mollis, porttitor dui at, finibus magna. Aliquam id efficitur lectus, eu ultricies nibh. Nam et posuere mauris, eget hendrerit nisi. Curabitur non tortor enim.</p>
  </span>

  <center><button onclick="AdjustTextSize()" id="readMoreBtn">Read more</button></center>
</div>

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

I need assistance on updating a document in MongoDB using Node.js

I'm in the process of developing a feature that automatically updates a player's high score to their account when they achieve a new record. However, I'm struggling with how to search for a player by name and update their tag using mongoose. ...

Ensure that the tooltip is always displayed at the top of the table within a span

Hi there, I've created a table and added a tooltip using CSS. The tooltip appears when you hover over the <td> elements. If you're interested, here's the link to my JSFiddle: www.jsfiddle.net/4qzurb5w/ I'm wondering how I can m ...

What did I overlook in my AJAX implementation?

When a user selects a value from the dropdown menu, an Ajax call must be made to the server to retrieve some values in JSON format. Below is the Ajax code //AJAX Security $('#ddlSecurityLevel').change(function () { if ($('#ddlSecurityL ...

Having trouble converting a string to a date format in Firefox using JavaScript code

Having trouble converting a String to date format in Firefox, but it works perfectly in Chrome. Check out the code snippet below: <input type="hidden" name="userDate" id="userDate" value="26-Aug-2014"/> <script> $(document).ready(function ( ...

How come the function is being triggered by my onclick button as soon as the page loads?

Currently, I am experiencing a challenge in my NodeJS project with Express. The issue lies with my EJS client side file when it comes to handling button click events. In my EJS file, I have imported a function from a JS file and can invoke it using <% ...

Graph not displaying dates on the x-axis in flot chart

I've been attempting to plot the x-axis in a Flot chart with dates. I've tried configuring the x-axis and using JavaScript EPOCH, but have had no success so far. Here's a snippet of my code: <?php foreach($data[0] as $i => $d){ ...

What could be causing the never-ending page reloads on a PWA Vue application?

I'm currently working on turning my Vue app into a PWA using the Vite-PWA-plugin (this plugin) However, I've encountered an issue where the page keeps reloading repeatedly when served from cache, especially when utilizing the Oauth2 protocol for ...

Invoke callback function to manage modal visibility

My project includes a modal for displaying a login/register form. The default behavior is that the modal opens when triggered by another component using the props show. This setup works perfectly when the modal is called by this specific component. Furthe ...

Struggling to iterate through the children of a variable with the help of express-handlebars?

Currently, I am in the process of developing an application using Javascript along with express, express-handlebars, and MySQL. One of my main tasks is to establish a route that follows the pattern '/viewowner/:ID/scoreboards/:year' where ID sig ...

When I tried to retrieve the value by using deferred.resolve(value) in my .then() method, it

I am currently utilizing Q.js to make an API call with two loops in my main function structured like this: for i..10 for i...5 var promise = getLoc(x,y); promise.then(function(value) { //value is undefined... ...

Automatically generating new lines of grid-template-columns with CSS grid

I am new to using grid in CSS and there are still some concepts that I don't quite understand. Below is the container I am working with: <section class="css-grid"> <div class="css-item"><img src="1.jpg" / ...

CSS magic: Text animation letter by letter

I have a <div> with text. <div> to be revealed on the page one character at a time:</p> <div>, the animation should stop and display the full text instantly.</p> In summary, I aim to replicate an effect commonly seen in Jap ...

Steps for incrementing a number in an integer field with Node.js and MongoDB

I have a dataset that looks like this: { "_id": "6137392141bbb7723", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="95f7e7fafafef0d5f6f4f2f9f0bbf6faf8">[email protected]</a>", ...

Guide on making a persistent sidebar using CSS and JavaScript

I'm in the process of developing a website that features a main content area and a sidebar, similar to what you see on Stack Overflow. The challenge I am facing is figuring out how to make the sidebar remain visible as a user scrolls down the page. T ...

What is the best way to update an array in TypeScript when the elements are of different types and the secondary array has a different type as

const usersData = [ { "id": 0, "name": "ABC" }, { "id": 1, "name": "XYZ" } ]; let dataList = []; // How can I transfer the data from the user array to the dataList array? // If I use the map function, do I need to initialize empty values for oth ...

Which CSS 3 transition prefixes are recommended for optimal performance?

I'm curious about the CSS vendor prefixes needed for transitions. One source mentions that "you need to use all the usual prefixes to make this work in all browsers (-o-, -webkit-, -moz-, -ms-)". Another page only displays the -webkit- and -moz- pre ...

CSS - Positioning a rectangle between two squares

I need help creating a layout with 2 rows of 4 squares, each with a rectangle in the middle of two squares. https://i.sstatic.net/9pWBi.png This is the code I currently have: .main { width: 100%; height: auto; } .square { width: 25%; position: ...

Javascript is utilized to populate text within a div, although the animation is exclusively applied to the initial text

I am currently working on designing a landing page that showcases a dynamic display of rotating texts with a typewriter-like animation effect. While I have successfully implemented the animation for the first text, I am facing an issue where the subsequent ...

Transform the ISO 8601 date format into another ISO 8601 format with the help of MomentJS

Can a date format like the following: 2003-09-25T14:00:00.000+1000 or 2003-09-25T14:00:00.000+1100 Be converted to this format? 2003-09-25T14:00:00.000Z Using only MomentJS without any manual intervention. Additionally, I would like to understa ...

`validate.js verifying the elements within an array`

One of the challenges I'm facing in my JavaScript project is dealing with objects that have two array properties included. As part of my development process, I've decided to utilize the resources provided by the validate.js library. To illustrat ...