Reveal and conceal using CSS animations

I am working on adding animation effects to show and hide HTML elements triggered by a button click. The button toggles a "hide" class to display or hide the element.

Check out my code snippet:

const toggleButton = document.querySelector('button');
const elementToToggle = document.querySelector('.box');

toggleButton.addEventListener('click', () => {
  elementToToggle.classList.toggle('hide');
})
.box {
  width:200px;
  height: 200px;
  border: 1px solid #000;
  background-color: gray;
  margin: 0 auto;
  opacity: 1;
  display: block;  
}

.hide {
  display: none;
  transition: all 1s ease-out;
  opacity: 0;  
}
<button>Show / Hide</button>
<div class="box hide"></div>

Answer №1

If you are looking to incorporate animations, avoid using display:none. Instead, consider utilizing visibility

const button = document.querySelector('button');
const box = document.querySelector('.box');

button.addEventListener('click', () => {
  box.classList.toggle('hide');
})
.box {
  width:200px;
  height: 200px;
  border: 1px solid #000;
  background-color: gray;
  margin: 0 auto;
  opacity: 1;
  transition: all 1s ease-out;
  visibility: visible;  
}

.hide {
  visibility: hidden;
  transition: all 1s ease-out;
  opacity: 0;  
}
<button>Show / Hide</button>
<div class="box hide"></div>

Answer №2

To make your hide feature work smoothly, simply remove the display: block from your code. Additionally, if you want to add animation to the div when it shows, include the appropriate animation in your CSS:

const button = document.querySelector('button');
const box = document.querySelector('.box');

button.addEventListener('click', () => {
  box.classList.toggle('hide');
})
.box {
  width:200px;
  height: 200px;
  border: 1px solid #000;
  background-color: gray;
  margin: 0 auto;
  opacity: 1;
  transition: all 1s ease-out;
}

.hide {
  transition: all 1s ease-out;
  opacity: 0;  
}
<button>Show / Hide</button>
<div class="box hide"></div>

Answer №3

I set out on a similar quest, but the solution eluded me here. Hopefully, my code can serve as a beacon for others seeking answers.

Feel free to request any modifications if necessary.

This is my code :

<!DOCTYPE html>
<html lang="fr" style="position: absolute; top: 0; left: 0; font-size: 16px; margin: 0; padding: 0; width: 100%;">
  <head>
    <title>Test of Div reveal</title>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta content='width=device-width, initial-scale=1' name='viewport'/>
  </head>
  <body style="margin: 0; padding: 0; width: 100%; background: #90ee90;">
    <style>
      div.hidden-stuff-container {
        overflow-y: hidden;
        overflow-x: scroll;
        width: calc(100% - 40px);
        margin: 10px;
        padding: 10px;
        background: rgba(0, 0, 0, 0.1);
        transition: all 1s;
      }
      div.hidden-stuff-title {
        display: inline-block;
        margin: 0;
        padding: 0;
      }
      span.hidden-stuff-arrow {
        transform: rotate(45deg);
        border-top: 1px solid black;
        border-left: 1px solid black;
        display: inline-block;
        width: 10px;
        height: 10px;
        position: relative;
        top: 5px;
        transition: all 1s;
      }
      button.hidden-stuff-button {
        display: inline-block;
        font-family: initial;
        font-size: 1rem;
        border: none;
        border-radius: 0%;
        padding: 5px;
        margin: 0;
        background: rgba(0, 0, 0, 0);
      }
      button.hidden-stuff-button:hover {
        background:rgba(0, 0, 0, 0.1);
      }
      div.hidden-stuff {
        display: none;
        opacity: 0;
        transition: all 1s;
        margin: 0;
        padding: 10px;
        background:rgba(255, 255, 255, 0.2);
      }
    </style>
    <script type="text/javascript">
      async function show_hidden_stuff(hidden_stuff_id){
        let hidden_stuff_container = document.getElementById(hidden_stuff_id + '-container');
        let hidden_stuff_container_initial_size = document.getElementById(hidden_stuff_id + '-title').offsetHeight;
        let hidden_stuff_container_current_size = hidden_stuff_container.offsetHeight - 20;//-20 because of padding
        let hidden_stuff_arrow = document.getElementById(hidden_stuff_id + '-arrow');
        let hidden_stuff = document.getElementById(hidden_stuff_id);
        let hidden_stuff_container_max_size;
        if(hidden_stuff.style.display == 'block'){
          if(hidden_stuff_container.style.height == 'auto'){//Wait for the openning to end
            //It's required that the div has a fixed size for the animation to work
            hidden_stuff_container.style.height = hidden_stuff_container_current_size + 'px';
            //And it's also somehow required to wait
            await new Promise(wait=>setInterval(wait, 1));
            hidden_stuff.style.opacity = '0';
            hidden_stuff_arrow.style.top = '5px';
            hidden_stuff_arrow.style.transform = 'rotate(45deg)';
            hidden_stuff_container.style.height = hidden_stuff_container_initial_size + 'px';
            await new Promise(wait=>setInterval(wait, 1000));
            hidden_stuff.style.display = 'none';
          }
        }
        else{
          hidden_stuff_container.style.height = hidden_stuff_container_initial_size + 'px';
          hidden_stuff.style.display = 'block';
          //It's somehow required to wait after setting display from none to block for opacity transition to work
          await new Promise(wait=>setInterval(wait, 1));
          hidden_stuff.style.opacity = '1';
          hidden_stuff_arrow.style.top = '-2px';
          hidden_stuff_arrow.style.transform = 'rotate(-135deg)';
          hidden_stuff_container_max_size = hidden_stuff_container_initial_size + hidden_stuff.offsetHeight;
          hidden_stuff_container.style.height = hidden_stuff_container_max_size + 'px';
          await new Promise(wait=>setInterval(wait, 1000));
          //Allow dynamic resizing (ex: when we turn our phone)
          hidden_stuff_container.style.height = 'auto';
        }
      }
    </script>
    <div class="hidden-stuff-container" id="somestuff-container">
      <div class="hidden-stuff-title" id="somestuff-title"><button class="hidden-stuff-button" onclick="show_hidden_stuff('somestuff')">TITLE&#160;&#160;<span class="hidden-stuff-arrow" id="somestuff-arrow"></span></button></div>
      <div class="hidden-stuff" id="somestuff">
        TEXT
      </div>
    </div>
    <div class="hidden-stuff-container" id="anotherone-container">
      <div class="hidden-stuff-title" id="anotherone-title"><button class="hidden-stuff-button" onclick="show_hidden_stuff('anotherone')">Lorem ipsum&#160;&#160;<span class="hidden-stuff-arrow" id="anotherone-arrow"></span></button></div>
      <div class="hidden-stuff" id="anotherone">
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ac tellus volutpat, viverra ligula vel, placerat lorem. Donec nunc ex, pretium et eros vel, posuere pretium velit. Fusce id commodo neque, eu tincidunt dui. Aliquam at ex pellentesque velit interdum fermentum sed at arcu. Vivamus at mauris justo. Cras ornare eleifend ullamcorper. Morbi dapibus semper aliquet.</p>
        <p>Nam eget quam non enim pellentesque blandit at ut urna. Nam dapibus risus eu libero venenatis dapibus. Cras a turpis eu leo luctus ornare in eu nulla. Interdum et malesuada fames ac ante ipsum primis in faucibus. Vestibulum ultricies risus ligula, eu hendrerit dui auctor quis. Donec non tempor nulla, sed accumsan lectus. Proin a metus varius, luctus odio at, dapibus lectus. Nunc a ornare turpis. Phasellus eget hendrerit ex, eget commodo augue.</p>
        <p>Nullam euismod egestas risus et lacinia. Suspendisse potenti. Ut sed libero enim. Sed pretium at nisi ut convallis. Sed at magna non metus tincidunt pretium. Etiam ac scelerisque elit. Suspendisse potenti.</p>
        <p>Curabitur purus lacus, lacinia nec sapien vel, maximus consectetur augue. Ut imperdiet malesuada odio, in vulputate mauris facilisis vel. Interdum et malesuada fames ac ante ipsum primis in faucibus. Praesent vitae lacinia ante. Quisque semper ex lacus, non accumsan mi.</p>
      </div>
    </div>
  </body>
</html>

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

Create a division that will remain visible on the screen and allow scrolling when a certain class is

Having some trouble with a fixed class div that is not continuing to scroll after the class is removed on scroll. I've attempted to fix this issue but the div keeps getting hidden instead of continuing to scroll. If anyone has any advice or can poin ...

Utilizing Custom Validators in Angular to Enhance Accessibility

I'm struggling to access my service to perform validator checks, but all I'm getting is a console filled with errors. I believe it's just a syntax issue that's tripping me up. Validator: import { DataService } from './services/da ...

Storing a temporary value within an ng-repeat iteration in AngularJS

A unique and interesting query arises when dealing with random value generation. Here is a snippet of code that showcases how to achieve this: function randomize() { return function (input) { if (input !== null && input !== undefined & ...

Displaying the division of shares in an HTML table using jQuery to add a new row

I recently worked on transposing a table, adding classes and ids to specific HTML tags, and converting numbers with commas into integers. Now, I am attempting to calculate the percentage share and display it in a new row. Here is the original table for re ...

Display PDF blob in browser using an aesthetically pleasing URL in JavaScript

Using Node, I am retrieving a PDF from the server and sending it to my React frontend. My goal is to display the PDF in the browser within a new tab. The functionality works well, but the URL of the new tab containing the PDF is not ideal. Currently, the U ...

Ways to extract a single digit from the total sum of a date in the format of 15-06-2015

Is there a way to extract a single digit from the sum of a number in date format, such as 15-06-2015? My goal is to convert the date format 15-06-2015 into a single-digit value by adding up the numbers. For instance: In the case of 15-05-2015, the output ...

Tips for confirming a date format within an Angular application

Recently, I've been diving into the world of Angular Validations to ensure pattern matching and field requirements are met in my projects. Despite finding numerous resources online on how to implement this feature, I've encountered some challenge ...

The function given to requestAnimationFrame is not being triggered as expected

I have successfully implemented an infinite loop animation using setInterval. However, I want to enhance the performance by switching to requestAnimationFrame(). Unfortunately, the function supplied to requestAnimationFrame() is not being called for some r ...

Assign a value to a jQuery variable from user input

Can someone assist me in setting an input field to the value of a jQuery variable? I am encountering difficulties with this task. My aim is to have equipment failure counts appear in an input textbox so that I can later write the value back to a table. Eac ...

Customize the appearance of the date input box in MUI KeyboardDatePicker

Currently, I am attempting to customize the appearance of the KeyboardDatePicker component including board color, size, font, and padding. However, none of the methods I have tried seem to be effective. Here is what I have attempted so far: 1 . Utilizing ...

Retrieve information from various MongoDB collections

Greetings! I currently have a database with the following collections: db={ "category": [ { "_id": 1, "item": "Cat A", }, { "_id": 2, "item": "Cat B" ...

Leveraging functions in a Node.js module

I am struggling with using a function inside a Node.js module. I have implemented a custom sorting function to sort an array of objects based on the value of a specific property. exports.getResult = function(cards) { cards.sort(sortByField('suit& ...

I have configured my CSS styles in the module.css file of my Next.js application, but unfortunately, they are not being applied

I recently developed a nextjs with electron template application: Here is the link to my code on CodeSandbox: https://codesandbox.io/s/sx6qfm In my code, I have defined CSS classes in VscodeLayout.module.css: .container { width: '100%'; he ...

Dependency on the selection of items in the Bootstrap dropdown menu

I am currently struggling with a few tasks regarding Bootstrap Dropdown Selection and despite looking for information, I couldn't find anything helpful. Check out my dropdown menu Here are the functions I would like to implement: 1) I want the subm ...

Creating dynamic PDFs with automatically adjusting heights in DOMPDF Learn how to make

It seems like this question may not have a straightforward answer, but let's give it a shot. My goal is to collect various information from users on my website and display it in an HTML template file that will later be converted into a PDF. With user ...

Launching an embedded webpage in a separate tab within the main browser window

In my current setup, I have implemented an iframe within the main window. The iframe includes a form where users can input data and submit it. Currently, I achieve the submission with the following code: var openURL = '/results/finalpage'; windo ...

Mastering various techniques for creating styles with makeStyles in React JS Material-UI

As a newcomer to React JS and Material UI, I am experimenting with creating various styles of buttons. Each button should have a unique appearance based on attributes like name= submit, ok, cancel, confirm, alert. App.JS import CssButton from './con ...

Is it possible to access the DOM element within which the registerHelper is being used?

My current challenge involves using Template.registerHelper to create a helper that can output either class1 or class2 based on a boolean value. Additionally, I want the output to include an initial class only if it's the first time the helper is call ...

What is the best way to adjust the decimal values in my API calls?

Is there a way to adjust the numerical data returned by the API to display only two decimal places instead of three? For example, if the number is 140.444, I want it to show as 140.44 What changes do I need to make? function fetchData() { fetch(" ...

Struggling with validating forms with JavaScript

I'm having trouble with the following JavaScript code: <script type="text/javascript"> function checkDetails(search) { var search = documment.getElementById('query'); if(search.value ==''||search.val ...