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

How can the value of a button be displayed in an input box using an onclick function?

When the button '1' is clicked, it displays the value "1" inside a <!p> tag. However, the second button '2' does not display the value "2" in the input box. Even though both functions are identical. //Function with working func ...

Elements with absolute positioning are preventing drag events from executing

Struggling to create a slider and encountering an issue. The problem lies in absolute items blocking slider drag events. I need a solution that allows dragging the underlying image through absolute positioned items. Any ideas on how to achieve this? MANY T ...

Can the garbage collector in Typescript/JavaScript effectively handle circular references, or does it result in memory leaks?

When working in languages such as C#, managing memory is not a problem. However, this can lead to difficult-to-find memory bugs in other languages. Is it safe to use the following code snippet in Typescript or Javascript without encountering any issues? c ...

Stop automatic page refresh after submitting a jQuery post request

I've tried various solutions, but unfortunately, neither e.preventDefault() nor return false seem to be working for me. When I use prevent default ajax doesn't make post request. Even using $.post doesn't work as expected. Furthermore, addin ...

Using async and await inside a setTimeout function within a forEach loop

Currently, I am facing a challenge with scheduling background jobs in Node.js. I need each job to run only after the previous one has finished. Below is the code snippet inside a function: jobArray.forEach((item, i) => { setTimeout(async () => { ...

Tips for showcasing JavaScript variables on a webpage

I am working with various JavaScript variables that involve displaying values inside div elements. goalDiv = "<div class=goal-parent id=goal-parent"+Id+">"+ "<div class=goal>"+ "<div class=top-layer>"+ "<div class=compone ...

Guide to retrieving the previous URL in Angular 2 using Observables

Can someone help me retrieve my previous URL? Below is the code snippet I am working with: prev2() { Promise.resolve(this.router.events.filter(event => event instanceof NavigationEnd)). then(function(v){ console.log('Previous ' ...

Increase value continuously when button is pressed down using Material UI

I am looking for a way to continuously increment a value while holding down a button. I have already managed to make it increment on click, but now I want to keep it increasing as long as the button is held down. How can this be achieved using material u ...

Middle-Click JavaScript Action

On the website I'm currently working on, there is a button that uses a sprite sheet animation and therefore needs to be set as a background image. I want the button to have a slight delay when clicked, so the animation can play before redirecting to a ...

Structural directive fails to trigger event emission to parent component

Following up on the question posed here: Emit event from Directive to Parent element: Angular2 It appears that when a structural directive emits an event, the parent component does not receive it. @Directive({ selector: '[appWidget]' }) export ...

Verify whether a certain key exists within the gun.js file

Suppose I need to verify whether a specific entry exists in the database before adding it. I attempted the following: gun.get('demograph').once((data, key) => { console.log("realtime updates 1:", data); }); However, I only receive ...

Is there a way to leverage JavaScript to click on one div and modify the settings of another div simultaneously?

I am struggling with my code which has unnecessary information. <div> <div id="one" class="button"></div> <div id="two" class="button"></div> </div> <div> <div class="Home tab"> < ...

Converting JSON into Typescript class within an Angular application

As I work on my app using angular and typescript, everything is coming together smoothly except for one persistent issue. I have entity/model classes that I want to pass around in the app, with data sourced from JSON through $resource calls. Here's ...

What could be causing the decrease in speed of my Three.js animation within Vue.js?

I attempted to replicate the impressive wave simulation from this CodePen link: https://codepen.io/cheekymonkey/pen/vMvYNV, using Vue.js. However, the animation seems to be running significantly slower when implemented in Vue.js. In my effort to recreate ...

Best Practices for Installing Webpack in a Client/Server Folder Structure

Working on a React Nodejs web application and in the process of figuring out how to bundle the frontend using webpack. This is how my project's structured: Where exactly do I need to install webpack and configure webpack.config.js? I've noticed ...

leveraging an array from a separate JavaScript file within a Next.js page

I am facing a situation where I need to utilize an array from another page within my Next.js project. However, it seems that the information in the array takes time to load, resulting in encountering undefined initially when trying to access it for title a ...

Having trouble getting the Underscore.js template to function correctly with JSON data

Hello there! I have some PHP code $arr = array("title"=>"sample Title", "body"=>"151200"); echo json_encode($arr); The data output is: {"title":"test Title","body":"151200"} When I attempt to use this JSON output in Underscore, I encounte ...

Passing dynamically loaded parameters to a function during dropdown value selection in Angular 2

Could you please review if I am passing the parameters correctly in the li tag's click function of the updateId method? The console errors only point to that line. This is my app.component.html code: <div class='form-group' style="width ...

Guide to shutting down a print dialogue in a web browser with javascript

Looking for a way to close the print window of a browser using JavaScript or any other method, with JavaScript being the preferred option. Any help on closing the print window for IE, Chrome and Safari would be greatly appreciated. Please assist.. Thank ...

Adjust the angle and trim an image on one side

Can someone assist with making an image appear like this: I'm attempting to achieve this look using CSS: I've experimented with skewing but the red area persists, regardless of the degree value used. Here is my basic structure: <div class= ...