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

What steps should be taken to validate an HTML5 form without actually submitting it?

I am working on a form that includes various HTML attributes such as: <form> <label>Full Name</label> <input type="text" name="firstname" class="span3" required="required"> <label>Email Address</label&g ...

Unable to get CSS transition to function properly after adding a class using jQuery

I am trying to create a hover effect that shows an image when the mouse is over a specific div, but for some reason, the transition is not working as expected. I understand that using visibility: hidden cannot be animated. Here is the code snippet: $(d ...

Adjust the tabs to fit perfectly within the container

I am currently facing an issue with my navigation bar. I have placed the <nav> tags within a container set to 100% width. However, when I adjust the height of the container by a certain percentage, the <ul> & <li> elements in the nav ...

Multiplication and Division with Unit-ed Values in CSS calc() Function

Can you perform multiplication or division with unit-based values using calc() (such as 100%, 5px, etc)? For instance, I wanted to try something like this: width: calc(100% * (.7 - 120px / 100%)); Expecting it to result in something similar to (if 100% ...

Steps to remove a row from a table in a ReactJS component

I'm struggling with implementing a delete operation for table rows and encountering errors. Any assistance in resolving this issue would be greatly appreciated. Since I am unsure how to set an auto-incrementing id, I used Date.now(). Now my goal is t ...

Play framework fails to apply style attributes correctly

When working with play-framework 2.3.x, I am in the process of creating a form and would like to show/hide it based on a model attribute. Typically, setting the style attribute manually using style = "display: none" and style = "display: block" works fine. ...

The process of adding a tooltip icon to a Select component in Material-UI

I'm currently working with the material UI tooltip component and I want to position my tooltip to the right of a dropdown, right next to the down arrow as shown in the image below: https://i.stack.imgur.com/O2gwh.png However, the way it is set up no ...

Can someone help me transform this LESS code into SCSS?

Currently, I am working on adapting a theme from [www.bootswatch.com][1] that is originally in less format to scss for my rails application. Although I am not well-versed in either SCSS or LESS, I have been researching the variances and have identified so ...

The Tumblr HTML code is not valid: There is a stray start tag for `html

Occasionally, I check my tumblog for validation in order to fix any errors. While most issues are easy to explain, there is one that has me stumped. What exactly does this mean? (please note: the outputted markup is out of my control) Error: Error: Stra ...

The press of the Enter key does not trigger the button

I'm facing an issue with a form that has just one field for user input and a button that triggers some jQuery to hide the login form when clicked. However, pressing enter after entering text causes the page to refresh... I'm starting to think th ...

Managing the load more feature with a Selenium script using Python

As a newcomer to Python, I am experimenting with automating clicks on the "load more" button found in the comment section of Instagram using Selenium and Python. Despite being able to click once successfully, the button disappears after the first click. ...

Switch the input direction from left to right

Check out my demonstration that is currently functional: JSFIDDLE $('#btn-search').on('click', function(e) { e.preventDefault(); $('#search').animate({width: 'toggle'}).focus(); }); Is there a way to modify ...

How to retrieve a value from an Angular form control in an HTML file

I have a button that toggles between map view and list view <ion-content> <ion-segment #viewController (ionChange)="changeViewState($event)"> <ion-segment-button value="map"> <ion-label>Map</ion-label> & ...

Manipulating Width in CSS

I am facing a challenge with the HTML code below where an automated software inserts the initial CSS style g2f0 <div class="linelevel row"> <div class="g2f0 col-sm-6 form-group"> <label for="name">Name</label> < ...

What is the best way to alter the text color based on certain conditions within a table column using PHP

I am faced with multiple conditions involving if-else statements, where the variable "Remark" changes based on these conditions. if($income==($paid + $deduction)){ $remark="Paid"; } else if($paid > 0){ $remark="Have Due"; } else{ $remark="N ...

What's the reason for the element not inheriting margins from its parent?

I am facing an issue with centering an h1 header within a .banner element. When I try to apply margin to the header, it appears to indent not from the top border of the banner, but rather from the nav element located above the banner. After inspecting the ...

Using Node.js and Express, the CSS does not load due to route parameters

I'm currently working on a basic website project using Node.js, Express, and the EJS template engine. I've run into an issue where my external CSS files are not loading properly on routes that contain route parameters. Here's a snippet of my ...

The conversion of a newline in an Angular page is done using &lt;br/&gt tag

Here is a function I have: setLocalVariableOnAccepted(ogp, hb, responseJson) { if (responseJson.ofgp === undefined) { this.ogpStatus = 'orange'; this.ogpStatusMsg = responseJson.ofgp + ', <br/> No change. Previous va ...

unassigned variables in a PHP email submission form

My PHP email form is not sending emails because my variables are coming up as null. I have an echo statement after my code to check if the variables have values, but they are not being printed. Only 'done' and 'email $to' are showing up ...

Having trouble getting the hover effect to change the colors of CSS borders

I am experiencing difficulty in changing the background color of the 'About' button to yellow and the border color to blue when it is hovered over. Currently, only a small rectangle around the text changes to yellow on hover and I cannot figure o ...