Animate div visibility with CSS transitions and Javascript

I'm currently working on incorporating an animation into a div that I am toggling between showing and hiding with a button click. While I have the desired animation, I am unsure of how to trigger it using JavaScript when the button is clicked. Can anyone provide assistance with this issue?

https://codepen.io/mattmcgilton/pen/JjjbGMB

.reveal-content {
    animation: slide-in-fwd-center 0.4s cubic-bezier(0.250, 0.460, 0.450, 0.940) both;
}


 @keyframes slide-in-fwd-center {
    0% {
      transform: translateZ(-1400px);
      opacity: 0;
    }
    100% {
      transform: translateZ(0);
      opacity: 1;
    }
  }
var x = document.getElementById("reveal-content").style.display = "none";

document.getElementById("btn-reveal").addEventListener('click', function() {
    var x = document.getElementById("reveal-content");
    if (x.style.display === "none") {
      x.style.display = "block";
    } else {
      x.style.display = "none";
    }
});

Answer №1

If you want to hide and show an element using a smooth transition, you can set a max-height for the element and apply the necessary CSS transitions. See the code snippet below:

document.getElementById("btn-reveal").addEventListener('click', function() {
  let el = document.getElementById('reveal-content');
  if (el.classList.contains('hide')) {
    el.classList.remove('hide');
  } else {
    el.classList.add('hide');
  }
});
.wrapper {
  overflow: hidden;
}

#reveal-content {
  max-height: 1000px;
  transition: all 0.5s ease-in;
}

.hide {
  max-height: 0 !important;
  transition: all 0.2s ease-out;
}
<button type="button" id="btn-reveal" class="btn">Button</button>
<div class="wrapper">
  <div id="reveal-content" class="hide">
    <h2>Hide me and then reveal me</h2>
    <div id="json-content">
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc scelerisque dui magna, imperdiet ultricies felis pellentesque nec. Aenean iaculis tellus porttitor sapien sagittis, eu dapibus dui ultricies. In gravida arcu leo, sit amet convallis quam
        tincidunt tempus. Aliquam eget suscipit tortor. Maecenas eget nunc eu risus auctor lacinia. Nulla et sapien sed urna ultrices pretium non ac purus. Quisque sed egestas augue. Aliquam sit amet vulputate tortor. Sed condimentum tellus eu placerat
        feugiat. Nullam quis eros sed magna venenatis condimentum. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere lacinia facilisis. Curabitur sit amet porta dui.</p>
    </div>
  </div>
</div>
<div>Rest of the page...</div>

Answer №2

To handle the displaying aspect, your CSS code is already doing the heavy lifting so there's no need to repeat that in JavaScript. What you actually need is the classList.toggle() method. By using this method, you can easily add and remove the .reveal-content class on a click event. Your JavaScript code should look like this:

var div = document.querySelector("div");
var button = document.getElementById("btn-reveal");
button.addEventListener('click', function () {
   div.classList.toggle("reveal-content");
});

UPDATE:

var div = document.querySelector("div");
var button = document.getElementById("btn-reveal");
button.addEventListener('click', function () {
    if(div.classList.contains('slide-in-fwd-center')) {
        div.classList.add("slide-out-bck-center");
        div.classList.remove("slide-in-fwd-center");
    }
});
button.addEventListener('click', function () {
    if(div.classList.contains('slide-out-bck-center')) {
        div.classList.add("slide-in-fwd-center");
        div.classList.remove("slide-out-bck-center");
    }
});

In your CSS code, only one of the classes (.slide-in-fwd-center or .slide-out-bck-center) will be applied as a default.

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

What is preventing me from assigning all padding values at once?

I attempted to modify all paddings of the html element using JavaScript, with the following code: const pd = 1 document.getElementsByClassName('board')[0].style.paddingRight = pd + 'px' document.getElementsByClassName('board') ...

The issue of gallery image loading with the galleryView jQuery plugin is causing problems

Hi fellow developers, I could really use some assistance. I've been working on implementing the jquery galleryview plugin for my image gallery (check out my gallery here). Unfortunately, I'm running into an issue where the gallery is not loading ...

I'm experiencing some issues with my scene in ThreeJS - the HDR background isn't displaying, and my cube

<style> body { margin: 0; } </style> <script async src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="afcadc82c2c0cbdac3ca82dcc7c6c2dcef9e8199819c">[email protected]&l ...

When attempting to modify an element in an array within a state-managed object, the input field loses focus

In attempting to address my issue, I have crafted what I believe to be the most concise code example. The main goal is to display a table on the page populated with exercise data retrieved from a database. This data is then assigned to an array of objects ...

What methods can be used to incorporate animation when the display attribute transitions to none?

Is there a way to add animation in a Vue app when replacing elements? I would like the transition from, for example, clicking on a div with 'Num 1' to the divs with class 'showing' not disappear abruptly but smoothly, such as moving to ...

Can you explain the rationale behind html and js?

I am experiencing an issue with my code. When I click on the "click" button, the color changes as expected but the console log is showing that the code is not working according to the logic I have implemented. Initially, the color is black which is correc ...

Why is my index.tsx file not properly exporting? (React + Typescript)

I've developed a basic Context Provider that I'd like to package and distribute via npm. To package my code, I utilized the create-react-library tool. In my project, I've set up an index.tsx file that should serve as the entry point for im ...

In Selenium IDE, the command to locate elements by ID works smoothly, but when using Java, the same

I encountered a challenge while trying to locate a dropdown box. Despite being able to make it work using an absolute path, I struggled with identifying the element by its xpath or id. It's quite frustrating and I'm struggling to find a solution. ...

:after pseudo class not functioning properly when included in stylesheet and imported into React

I am currently utilizing style-loader and css-loader for importing stylesheets in a react project: require('../css/gallery/style.css'); Everything in the stylesheet is working smoothly, except for one specific rule: .grid::after { content: ...

Issues with login validation in HTML when utilizing JSON and PHP

While creating a login form in HTML using JSON and PHP, I encountered an issue where the if statements in the success function were not working properly. However, the beforeSend and error functions are functioning as expected. Can someone assist me in iden ...

Acquiring HTML form data using JavaScript

Although it may seem trivial, I'm facing a challenge. I have an HTML form that is dynamically generated by JavaScript and populated with initial data fetched from the server. The form is displayed correctly with the pre-filled data. My goal is to allo ...

Animation in CSS/transform drifting out of view

I have a challenge with animating text to each corner of the screen, where the text is rotated in every corner. However, I am facing an issue where the text goes off-screen in the top right and bottom left corners. It seems like the rotation might be causi ...

Adjusting the image placement within a modal window (using bootstrap 3)

Behold, an example modal: <!-- Large Modal --> <div class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel"> <div class="modal-dialog modal-lg"> <div class="modal-content"> ...

If you want to retrieve the calculated value of a div using jQuery

I have a scenario where I have 3 list items (li) under an unordered list (ul). I am interested in finding the height of these list items, but without explicitly defining their height. So far, when inspecting with Firebug, I noticed that the computed height ...

PHP POST request with an additional value being sent

Greetings as this is my debut post! Currently, I am facing a challenge in my project. As seen in the screenshot provided, I have several names fetched from the database and displayed in the main menu. Upon clicking the "modal" button, a Bootstrap modal wi ...

What is the best way to send props to a component that is exported using a Store Provider?

I'm trying to export my react component along with the redux store Provider. In order to achieve this, I've wrapped the component with an exportWithState callback. However, I'm facing an issue where I can't seem to access the props that ...

The Angular 9 custom directive is malfunctioning on mobile devices

I recently created a custom directive in Angular 9 that allows users to input only digits and one decimal point. While the directive works perfectly on desktop, it seems not to function at all on mobile devices - almost as if it doesn't exist within t ...

Is there a sleek way to create a JavaScript function that can provide two string values as output?

I am looking to store values in a specific format: "somekey": "value1", "value2" My goal is to create a function that takes in "somekey" and returns "value1", "value2". Alternatively, I could initialize a collection in my JavaScript file and reference i ...

What are the best practices for running node in VSCode?

$ node test.js internal/modules/cjs/loader.js:883 throw err; ^ I have exhausted all possible solutions, including checking the PATH route for Node.js, restarting, and using different files. Despite the fact that I am able to retrieve the version when ...

Creating a visually appealing gantt chart in React Native using the react-google-charts library - here's how!

These are the current packages I am using: react-google-charts 1.5.5 react 16.0.0-beta.5 react-native https://github.com/expo/react-native/archive/sdk-22.0.1.tar.gz I am currently working on rendering a Gantt Chart and you can find an example here and a ...