Modal transitions in JavaScript appearing choppy

I came across a cool CSS effect that I really like for some popup modals in my application, but I'm encountering difficulties when the modal(s) are dynamically created in the DOM using JavaScript.

When the user triggers the button to 'open' the modal, it should smoothly transition, appearing to scale up in size. Everything works as intended when using just HTML and CSS, but when triggered by a click event in my JS code, the modal suddenly appears and disappears (if I set 'display: block'), or it's very choppy, or sometimes it doesn't work at all (if I use 'visibility: visible').

I have a hunch that perhaps it's not recognizing it as a 'transition', or maybe I am mistakenly trying to animate the blurred background instead of the modal itself.

This is the snippet of my CSS related to the modal:

.modal {
  display: none; <-- added to toggle states, might be causing the issue

  height: 100vh; 
  width: 100%;
  position: fixed;
  top: 0;
  left: 0; 
  background-color: rgba($color-black, .8);
  z-index: 999999;
  opacity: .98; 
  transition: all .3s;

  @supports(-webkit-backdrop-filter: blur(10px)) or (backdrop-filter:blur(10px)){
    -webkit-backdrop-filter: blur(10px);
    backdrop-filter: blur(10px);
    background-color: rgba($color-black, .3);
  }

  &__content {
    @include absCenter; 
    width: 75%; 
    background-color: $color-white;
    box-shadow: 0 2rem 4rem rgba($color-black, .2);
    border-radius: 3px;
    display: table; 
    overflow: hidden;
    opacity: 1; 
    transform: translate(-50%, -50%) scale(1);
    transition: all .5s .2s;
  }

Apologies for the messy JavaScript pseudo-code, but the actual implementation is as tangled as spaghetti...

dbRecord.forEach(el => {
   const button = document.createElement('button')
   button.innerHTML = <populate some html with db info>

   button.addEventListener('click', (e) => {
         modal.style.display = 'block' 
         modal.innerHTML = <set attributes from parent element>

         document.querySelector('.modalCloseButton').addEventListener('click') => {
                modal.style.display = 'none'
         }
         // Other actions...
  }
}

How can I achieve a smooth transition for the modal rather than an abrupt change?

Answer №1

I managed to successfully implement the transition in one direction. Perhaps this snippet of code will assist you in achieving the desired transition effect in the opposite direction. display property does not support transitions. Instead, set background and color to transparent. If your transition duration is set to 0.3s, use a setTimeout function to change it to display: none after 0.3 seconds.

var modal = document.querySelector('.modal');
var dbRecord = ['foo', 'bar']
dbRecord.forEach(el => {
  var button = document.createElement('button');
  button.innerHTML = 'populate some html with db info<br>' + el;

  button.addEventListener('click', (e) => {
    modal.querySelector('p').innerHTML = 'set attributes from parent element<br>' + el;
    document.querySelector('.modalCloseButton').style.display = 'block';
    modal.style.display = 'block';
    modal.style.backgroundColor = 'rgba(0,0,0,.8)';
    modal.style.color = 'white';

  });
  document.body.appendChild(button);
});
document.querySelector('.modalCloseButton').addEventListener('click', () => {
  modal.style.backgroundColor = 'rgba(0,0,0,0)';
  modal.style.color = 'transparent';
  document.querySelector('.modalCloseButton').style.display = 'none';
  setTimeout(() => {
    modal.style.display = 'none';
  }, 300)
});
.modal {
  display: none;
  height: 100vh;
  width: 100%;
  position: fixed;
  top: 0;
  left: 0;
  background-color: rgba(0, 0, 0, 0);
  z-index: 999999;
  color: transparent;
  transition: all .3s linear 0s;
}
.modalCloseButton {
  display: none;
}
<div class="modal">
  <p></p>
  <button class="modalCloseButton">&times;</button>
</div>

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

Fading away backdrop images for the header

I've created a header class in my CSS with the following styling- header { background-image: url('../img/header-bg.jpg'); background-repeat: none; background-attachment: scroll; background-position: center center; .backg ...

Filtering an Array of Objects on the Fly in Vue.js

I'm currently working on a Vue.js app where I need to dynamically apply filter values to an Array of objects based on their field values. Each object in the Array has various fields that I want to filter by. The challenge is that each field can have m ...

Tips for maintaining the visibility of the dynamic submenu while hovering over either the parent menu or submenu in vuejs

I'm currently working on a dynamic sidebar in vuejs and I need some assistance. The issue I'm facing is that I want the submenu to remain open when hovering over either the parent menu or the submenu itself. However, when I move the mouse away fr ...

Creating a full-width tab card with Bootstrap-Vue: A step-by-step guide

I stumbled upon something similar in the documentation for bootstrap-vue: A card with tabs: https://i.sstatic.net/HoVEC.png Now, how can I style the tabs to look like this: https://i.sstatic.net/dbsRj.png This is my current code: <b-card no-body ...

Which is the best option: saving data-containing objects in a separate .js file or in the database?

As I work on developing an RPG game web app, I am looking to store predefined details regarding skills and traits. For example, an array of objects that define attributes like "Battle-hardened grants +2 strength" and "Ruthless past results in -1 social." ...

"Discover the process of transforming HTML, CSS, and script files into a cohesive JavaScript format

I have developed a unique web chat widget from scratch using HTML, CSS, JavaScript, and AJAX calls. Now, my goal is to convert it into a script that can be easily embedded in any other websites or webpages. Similar to how third-party widgets work, users sh ...

Issue with Mongoose query for finding data in multiple columns

If a keyword matches in category.title, then it will provide a result; otherwise, it does not match with any other fields. Can someone point out what the issue might be here? I also attempted NewsModel.find().or(filters) without the $or key, but it still i ...

Save instantly while modifying an element

I am exploring the idea of incorporating an automatic save feature using javascript/jQuery. In my project, I have multiple instances (hundreds) of elements with ids starting with `overlay-rotation-bounding-box`. For instance, `overlay-rotation-bounding-bo ...

Next.js experiences slowdown when initializing props on the server side

I've been working on implementing SSR with Next.js. In my code, I'm fetching JSON data and using them as initial props. Everything works fine in development mode, but when I deploy to the server, fetching only works on the client-side (when navi ...

Maintain the fixed position of the horizontal scroll bar

I'm facing an issue with a popup window that displays a frameset. Within one of the frames, I'm using jQuery tabs to show some text. The problem arises when trying to display long text or when resizing the window, causing the horizontal scroll t ...

The HTML5 thumbs-up feature will not be visible when not logged in

I have searched high and low on the web and even visited #facebook, but with no luck. I have experimented with the FBXML code as well, and it seems that if you are not logged into Facebook, the Like button will not appear on the page. The strange thing is ...

Using an object does not result in updated data, while data changes are typically observed when using a variable

In the process of developing a function to update a custom checkbox upon clicking (without resorting to using the native checkbox for specific reasons). Here's the code snippet for the checkbox: <div class="tick-box" :class="{ tick: isTicked }" @ ...

React useState Error: Exceeded maximum re-renders. React enforces a limit on the number of renders to avoid getting stuck in an endless loop

Can someone help me troubleshoot the 'Too many re-renders' error I'm encountering? I've implemented the try, catch method along with React hooks like useState and setState. My goal is to fetch data from an API and display it on a ...

Error: Unable to return callback response from NodeJs function

I have a function that handles the process of reading a private key from the filesystem and generating a JWT token. The code successfully reads the file and creates a token, but it encounters an issue when attempting to callback to the calling function. De ...

The argument labeled as 'State' cannot be assigned to a parameter labeled as 'never'

I've recently delved into using TypeScript with React. I attempted to incorporate it with the React useReducer hook, but I hit a roadblock due to an unusual error. Below is my code snippet: export interface ContractObj { company: string; ...

Using Three.js, generate a series of meshes that combine to create a seamless 90-degree donut shape

I'm on a quest to discover an algorithm that can create the following shape in Three.js. Here is my rough sketch of the expected shape The number of meshes needed to form the 90 degree donut, as well as the thickness and spacing between them, should a ...

Fulfill the promise once all map requests have been completed

Currently, my focus is on developing a bookmark page that retrieves bookmark results with the respective restaurant IDs. Once the response is mapped, I populate an array with objects. My objective is to ultimately resolve the entire array in order to mani ...

The Bootstrap nav bar toggle feature is failing to toggle

My bootstrap navigation toggle does not seem to be toggling on click when the page shrinks. I have made sure to import the jQuery library first, so I'm not sure why it's not working. <!DOCTYPE html> <html lang="en" xmlns="http://www.w3 ...

unable to utilize references in React

import React, { Component } from "react"; class Learning extends Component { firstName = React.createRef(); handleSubmit = event => { event.preventDefault(); console.log(this.firstName.current.value); } ...

Issue with accessing Protractor spec file location

As a newcomer to Protractor, I followed a tutorial on GitHub to set everything up. The tutorial was successful, but when I tried to apply it to my actual code, I encountered a problem. I found that I can only call the spec.js file if it's located in t ...