Ways to switch text on and off smoothly using transitions

I have created a webpage where text starts off hidden but has a visible heading. When you click on the heading, the text is revealed below. I am putting the final touches and aiming to make the text slide in smoothly. I am using Javascript for toggling instead of jQuery. While I would prefer a CSS-only solution, I am also open to using Javascript. Below is the HTML content with Javascript controlling the toggle:

I attempted a CSS-only approach (shown below) which was unsuccessful;

function view(id) { //this function reads the div id variable passed in with each 'onclick' trigger
  var x = document.getElementsByClassName("descriptions"); // this will find all descriptions that have the "description" class
  var i;
  for (i = 0; i < x.length; i++) {
    if (x[i].id !== id)
      x[i].style.display = "none"; //turn off all descriptions except the current one
  }
  var e = document.getElementById(id); //toggle on/off the active description
  if (e.style.display == 'block')
    e.style.display = 'none';
  else
    e.style.display = 'block';
}
.descriptions {
  display: none;
  height: 100;
  transition: height 0.8s;
}
<div class="toggle" id="a" onclick="view('a1');">
  Chocolate cake with Nutella icing
  <div id="a1" class="descriptions">
    How to make a chocolate cake.
  </div>
</div>

Answer №1

One technique to consider is using the CSS property opacity in combination with transition.

function toggleDescription(id) {
  var descriptions = document.getElementsByClassName("descriptions");
  var i;
  for (i = 0; i < descriptions.length; i++) {
    if (descriptions[i].id !== id)
      descriptions[i].style.opacity = 0;
  }
  var activeDesc = document.getElementById(id);
  if (activeDesc.style.opacity == 0)
    activeDesc.style.opacity = 1;
  else
    activeDesc.style.opacity = 0;
}
.descriptions {
  transition: all 0.3s;
  opacity: 0;
  height: 100;
}
<div class="toggle" id="a" onclick="toggleDescription('a1');">
  Chocolate cake with Nutella icing
  <div id="a1" class="descriptions">
    How to make a chocolate cake.
  </div>
</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

React-native horizontal sliding plugin

Can anyone recommend a reliable horizontal slider plugin for react-native? I've come across some options, but they haven't been working as smoothly as I'd hoped. ...

Analyzing a CSV file and executing asynchronous operations on specific columns with the help of ajax requests

I possess a CSV file that contains placement links and target links formatted as follows: CSV Example [placement url],[target url] [placement url],[target url] [placement url],[target url] My objective is to parse the CSV file line by line using JavaScri ...

What is the best way to store article IDs using Javascript or HTML?

On my web page, I have a collection of links that users can interact with by clicking and leaving comments. These links are loaded through JSON, each with its unique identifier. But here's my dilemma - how can I determine which link has been clicked? ...

The local time displayed by Moment JS is not accurate and matches the time stored in the database

Is there a solution to displaying the createdAt field date based on the local timezone? I've attempted to implement it, but it only seems to work for localhost. When I upload it to the server, it displays the createdAt field data in UTC format. Below ...

Incorporating a teaser of a webpage into an <a> tag linking directly to the page

I am looking to enhance the <a> tag on my HTML page by including a URL link that directs users to another page, while also displaying a preview of that page. Similar to how Facebook automatically generates a preview when you post a link, I want to ...

Enhance your text in TextInput by incorporating newline characters with advanced editing features

I'm encountering an issue with my Textarea component that handles Markdown headers: type TextareaProps = { initValue: string; style?: StyleProp<TextStyle>; onChange?: (value: string) => void; }; type OnChangeFun = NativeSynthetic ...

Changing the selection in the Angular Mat-Select dropdown causes the dropdown's position to shift

Issue with dropdown position: The dropdown should display below the select element, but when selecting the second value, it appears on top of the select element. I have removed any relevant CSS to troubleshoot, but the problem persists. See screenshots for ...

Avoid invoking the throttle function from lodash

I am currently facing an issue in my React project with a throttle function from lodash. The requirement is that the function should not be executed if the length of the parameter value is zero. I have tried checking the length of the value and using thro ...

Running PHP code within an HTML file served by PHP

A unique and innovative approach was taken by incorporating a DIV element in the HTML code, which dynamically populates with content from the main_login.php file. The main_login.php file plays a crucial role in loading the homepage with member-specific con ...

List the acceptable favicon formats for Internet Explorer version 10 and above

When I say type, I'm referring to the file extension. My favicon displays correctly in Firefox, Chrome, and Safari, but someone suggested that the issue may be related to the favicon type. Is there a reliable online resource where I can find informa ...

Implementing a NextJS client component within a webpage

I am currently working with NextJS version 14 and I am in the process of creating a landing page. In one of the sections, I need to utilize the useState hook. I have specified my component as "use-client" but I am still encountering an error stating that " ...

Displaying an RSS feed inside a designated div element

Seeking assistance from all you wonderful individuals for what seems to be a simple problem. Here is the HTML code I am working with: <div id="rssfeed"></div> Along with JavaScript that includes the FeedEK plugin $(document).ready(function ...

Auth0 encountering issues retrieving ID token and user metadata

Currently in the process of integrating Auth0 into a Vue.js/Node.js application, I have successfully enabled user registration and login functionality (to /callback). Although the manual addition of data to the user metadata section is functional at this s ...

Arranging a dictionary by its keys using Ramda

My task involves manipulating an array of items (specifically, rooms) in a program. I need to filter the array based on a certain property (rooms with more than 10 seats), group them by another property (the area the room is in), store them in a dictionary ...

Adjusting Text Color on Buttons

I am looking for a simple button with clear color and black text, but the default button has white text. I need a way to change the text color. Check out my current app <View style={styles.fastlog}> <Button style={styles.bouton} title= "Con ...

Is it possible for an HTML file to not recognize an external CSS stylesheet?

I've been trying everything, but I can't seem to get these two documents to work together. I'm confident that the CSS file is linked correctly with the right file name. I decided to give it a shot after watching this coding blog tutorial on ...

Expanding and collapsing all divs with a single click using Jquery

I've gone through numerous resources but I'm still struggling to understand this concept. I have implemented a simple accordion based on this tutorial and now I want to include an "expand/collapse all" link. While I was able to expand all the ite ...

Encountered an error while trying to retrieve data from

Having trouble with file uploads to the S3 bucket using @aws-sdk/client-s3 library and encountering errors when uploading files larger than 70kbps: `TypeError: Failed to fetch at FetchHttpHandler.handle (fetch-http-handler.js:56:13) at PutObjectCommand ...

Is there a way to incorporate a CSS file into this without explicitly mentioning the color?

I have successfully implemented a PHP solution for changing themes with a cookie that remembers the selected theme color when the user leaves the site. However, I now need to switch this functionality to JavaScript while still utilizing the CSS file. How c ...

Showcase pictures from a directory in real-time using a combination of jQuery and Bootstrap as the folder continues to fill up with images

Although I am just beginning to learn about UI, I have a question that seems important to me. In my application, there is a background thread that downloads images and saves them in a folder named "images". I want these images to be displayed in the UI as ...