Fade out with CSS after fading in

After setting an animation property on an HTML element to display it, I want the same animation in reverse when a button is clicked to hide it. How can I achieve this effect?

"Working Animation":

.modal {
animation: myAnim 1s ease 0s 1 normal forwards;
}
@keyframes myAnim {
  0% {
    opacity: 0;
    transform: translateX(-50px);
  }

  100% {
    opacity: 1;
    transform: translateX(0);
  }

}

HTML Structure:

<div id="myModal" class="modal fixed hidden z-1 w-full h-full bg-red-100 h-screen ">

<button id="myBtn" class="p-2 bg-yellow-400 rounded m-4 absolute right-0 text-xs font-bold ">
HIDE/SHOW..
 </button>

I am currently using JavaScript to show/hide the modal. How can I hide the modal with the same animation effect?

Answer №1

Develop two distinct classes, one responsible for displaying the modal and the other for hiding it.

Class for Display

.modal-display{
animation: display 1s ease 0s 1 normal forwards;
}
@keyframes  display {
  0% {
    opacity: 0;
    transform: translateX(-50px);
  }

  100% {
    opacity: 1;
    transform: translateX(0);
  }
}

Class to Hide the Modal

.modal-hide{
animation: hide 1s ease 0s 1 normal forwards;
}
@keyframes  hide {
  0% {
    opacity: 1;
    transform: translateX(0);
  }

  100% {
    opacity: 0;
    transform: translateX(-50px);
  }
}

Now utilize JavaScript to apply these classes to the modal's classlist when the button is toggled.

const btn = document.querySelector('mybtn');
const modal = document.querySelector('#myModal');

btn.addEventListener ('click', function toggleClass () {
    if(modal.classList.contains('display')) {
        modal.classList.add('hide');
        modal.classList.remove('display');
    } else {
        modal.classList.add('display');
        modal.classList.remove('hide');
    }
})

Answer №2

To achieve this effect, you can utilize the toggle class along with transition properties.

let btn = document.getElementById('model_btn');
let model = document.getElementById('model');
btn.addEventListener('click', function(){
  model.classList.toggle('show');
})
/* Custom styling for the elements */
#model{
  width: 200px;
  height: 100px;
  background-color: yellow;
  padding: 20px;
  margin-bottom: 20px;
}
#model_btn{
  border: none;
  background-color: green;
  padding: 10px;
  color: white;
  cursor: pointer;
}

/* CSS to handle show and hide animation */

#model{
  position: relative;
  visibility: hidden;
  opacity: 0;
  top: 0;
  left: 0;
  transform: translateX(-50px);
  transition: all 1s ease;
}
#model.show{
  visibility: visible;
  opacity: 1;
  transform: translateX(0px);
}
<div id="model">
  Content
</div>
<button id="model_btn">Show/Hide Model</button>

Alternatively, you can also create an animation using keyframes.

let btn = document.getElementById('model_btn');
let model = document.getElementById('model');
btn.addEventListener('click', function(){
  model.classList.toggle('show');
})
/* Custom styling for the elements */
#model{
  width: 200px;
  height: 100px;
  background-color: yellow;
  padding: 20px;
  margin-bottom: 20px;
  visibility: hidden;
  opacity: 0;
  transform: translateX(-50px);
}
#model_btn{
  border: none;
  background-color: green;
  padding: 10px;
  color: white;
  cursor: pointer;
}

.show{
  animation: myAnim 1s ease 0s 1 normal forwards;
}
@keyframes  myAnim {
  0% {
    visibility: none;
    opacity: 0;
    transform: translateX(-50px);
  }

  100% {
    visibility: visible;
    opacity: 1;
    transform: translateX(0);
  }
}
<div id="model">
  Content
</div>
<button id="model_btn">Show/Hide Model</button>

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

Leverage the greater than operator within an AngularJS controller

This is the data stored in my controller: $scope.data = [{ "F": "1,26,000" }]; $scope.data2 = [{ "F": "26,000" }]; Now I want to implement an if-else condition using this data: if (Number($scope.d ...

problem encountered when converting SVG HTML into SVG paths

Recently, I came across an interesting SVG file depicting a question mark enclosed in a circle. Intrigued by its design, I wanted to extract the paths from this SVG image so that I could integrate it directly into my codebase. Following some online tutoria ...

Creating a flexible Bootstrap 3 layout that responds to the size of a div, not just the screen

Having a web page layout with a main content area and a fixed-width sidebar is proving to be a challenge. I want the content displayed in both sections to be responsive, adjusting based on the size of their respective parent divs rather than the screen siz ...

Injecting variable styles into my VueJS component

I am currently working on developing a custom progress bar to visualize the percentage of completed tasks. The approach I am taking involves using v-bind:styles and passing {width: dynamicWidth + '%'} to regulate the progression of the bar. To ac ...

Issues with CSS transitions not functioning properly following the use of toggleClass()

I recently implemented a toggle-menu feature, which you can see in action on this demo. To enhance the toggle-menu, I added a CSS transition effect to div.nav-menu, utilizing max-height:0; and increasing it to max-height:480px;. However, after clicking t ...

Steps for moving data from a JavaScript variable to a Python file within a Django project

I have created a unique recipe generator website that displays each ingredient as an image within a div. When the div is clicked, it changes color. My goal is to compile the ids of all selected divs into one array when the submit button is clicked. I have ...

The placement of a material-ui component at the beginning of the render method can impact the styling of the following components in the hierarchy

After creating some styled components, I noticed that they were not rendering correctly for me. However, when I transferred the code to a codesandbox environment (which had a material-ui button in the template), the components rendered perfectly fine. It w ...

Struggling with the elimination of bullet points in CSS navigation bars

I'm having trouble removing the bullet points from my navigation bar. I've tried using list-style-type: none and even adding !important, but it doesn't seem to work. Strangely enough, everything looks fine in Chrome, but I get an error when ...

If a span element does not exist, a bullet can be added within it

Is there a way to add and remove a bullet from an li element with the selected class, only if there is no span already present? Currently, every time the link is clicked, a bullet gets added. What would be the best approach to avoid adding multiple bullets ...

The arrangement of a table, an iframe, and another table being showcased in close proximity

I need assistance in aligning a table, an iframe, and another table side by side without any breaks. Ideally, I would like all three elements to be centered on the page. It seems odd that they're not displaying next to each other as my screen is larg ...

What is the method for obtaining the WordPress user ID?

I am looking to incorporate a Twitter follow button for all site authors on every post. Below is the structure of the Twitter button: <a href="https://twitter.com/twitterapi" class="twitter-follow-button" data-show-count="false" data-lang="en">Foll ...

The table is refusing to align itself in the center

I've been struggling to center the text inside this table despite trying various solutions. Any help would be greatly appreciated. Here's the HTML code I have: <div id="paccount"> <table style="margin: 0 auto;"> <tr&g ...

CSS: The calc() function does not take into account the bottom padding when used in Firefox and Internet

I am encountering an issue with the calc() function in Firefox 32 and IE 11, where the bottom padding of a div is not being respected. However, this problem does not occur in Chrome and Opera. The main content section should have a fixed height while allo ...

Utilize Mapbox-GL.JS to animate several points along designated routes

I'm encountering issues with the following example: Animate a point along a route My goal is to add another point and routes in the same map container. Here's what I've tried so far: mapboxgl.accessToken = 'pk.eyJ1IjoicGFwYWJ1Y2t ...

Centering text both vertically and horizontally over an image using CSS

I've been attempting to center the div banner_title both vertically and horizontally within another div in this way... .box { text-align: center; } .banner_title { font-size: 32px; position: absolute; top: 50%; width: 100%; } .banner_titl ...

How to Align Navigation Bar Items to the Right in Bootstrap 4

I need some help with bootstrap. I've looked at various discussions on this topic and tried numerous solutions, but I still can't get it right. I want the logo to be on the left and the navigation links aligned to the right. Here's what I&ap ...

PHP - the button remains unchanged after submission

My Objective: Upon button press, I want to update the database table. Additionally, the button should change its color and text. Issue at Hand: The button fails to change unless I manually refresh the page. I attempted using echo "<meta http-eq ...

Is it possible to leverage React/Next.js for dynamically adding HTML content based on element IDs when integrating with Netlify forms?

Sorry if this question has already been addressed somewhere. I've spent hours searching and troubleshooting without success. I'm still in the process of learning React, as it's a new concept to me. I just need to implement it for a contact ...

What is the best way to retrieve the value of a textbox in AngularJS?

Trying my hand at creating a basic web page using angular. I've got 2 textboxes and 2 buttons - one to set a predefined value in a textbox, and the other to add some text. Here's the code snippet: <!DOCTYPE html> <html lang="en" ng-app ...

Unable to refresh CSS file

Struggling with updating my website stylesheet. Everything seems to be in place - files uploaded correctly, cache cleared, even manually refreshed the CSS file multiple times. The only solution that works is renaming the CSS file and updating the link. A ...