How can I incorporate a transition into my modal with JavaScript in CSS?

I've recently started learning CSS and while I've come across similar topics, none have provided the solution to my specific problem. After spending 2 hours experimenting with various CSS properties like hidden, transition, and display, I am now turning to this platform for help.

My question is: How can I create a smooth modal using CSS and Javascript?

Here's the CSS code:

/* The Modal (background) */
.modalestate {
  visibility: hidden; /* Hidden by default */
  position: fixed; /* Stay in place */
  z-index: 1; /* Sit on top */
  left: 25;

  top: 15;
  width: 100%; /* Full width */
  height: 100%; /* Full height */
  overflow: auto; /* Enable scroll if needed */
  background-color: rgb(0,0,0); /* Fallback color */
  background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
  transition: all ease 1s;
}

/* Modal Content/Box */
.modalestate-content {
  background-color: rgba(0,0,0,0.0);
  margin: 12% auto; /* 15% from the top and centered */
  padding: 22px;
  float:left;
  width: 550px; /* Could be more or less, depending on screen size */
   transition: all ease 1s;
}

/* The Close Button */
.closeestate {
  color: #aaa;
  float: right;
  font-size: 20px;
  font-weight: bold;
}

.closeestate:hover,
.closeestate:focus {
  color: whitesmoke;
  text-decoration: none;
  cursor: pointer;
}

The HTML divs for showing the modal and its content:

<div id="mymodelestate" class="modalestate">
 <div class="modalestate-content">
    <span class="closeestate">&times;</span>
    
    <div id="responsecontainer" align="center"></div>
    
    </div></div>

The Javascript code:

<script>
// Get the modal
var modal = document.getElementById("mymodelestate");

// Get the button that opens the modal
var btn = document.getElementById("btnestate");

// Get the <span> element that closes the modal

var span = document.getElementsByClassName("closeestate")[0];

// When the user clicks on the button, open the modal
btn.onclick = function() {
  modal.style.visibility = "visible";
}

// When the user clicks on <span> (x), close the modal
span.onclick = function() {
  modal.style.visibility = "hidden";
}

// When the user clicks anywhere outside of the modal, close it
window.addEventListener('click', function(event) {

  if (event.target == modal) {
    modal.style.visibility = "hidden";
  }
});</script>

Appreciate your assistance in advance!

Answer №1

What specific "transition" are you aiming to achieve? What kind of visual effect do you intend to implement on your modal? The intention behind your approach is not entirely clear; however, based on the usage of visibility:hidden/visible, I presume you're looking to create a gradual fade-in and fade-out transition when users interact with buttons within the modal.

If your goal is to incorporate a fade-in/fade-out animation, it's essential to set the opacity to 0 initially:

opacity: 0;

Then, when you want to reveal the modal, adjust the opacity to 1.

Nevertheless, you might encounter several challenges while implementing this technique. Nonetheless, it serves as a valuable learning opportunity to gain familiarity with the operational dynamics between HTML elements and CSS properties.

UPDATE: In alignment with my earlier comments, below is an illustrative example along with some guidance.

To begin with, consider the BODY element as the foundation of your webpage, analogous to a human body. You append various elements resembling individual body parts to it. Your utilization of z-index demonstrates a sound understanding in this regard, hence I won't delve extensively into this aspect. While more experienced developers may introduce complex discussions related to DOM specifics and attachment methods, let’s maintain simplicity for now.

Subsequently, every element features certain intrinsic attributes. For instance, a DIV element exhibits inline-block as its inherent attribute. Furthermore, a P tag comes with default margin settings and functions as a block-level component. You have the liberty to override these defaults via CSS or supplement additional attributes, similar to customizations you've been implementing by assigning CLASS values which define unique characteristics for each element (though they remain rooted in their base elements like DIV, P, A, SPAN, etc).

An in-depth comprehension of these attributes is equally crucial. Evidently, you possess considerable knowledge in this domain, thus there isn’t much need for elaboration except for the following:

  • Visibility - Despite remaining imperceptible, the element retains its presence within the BODY structure, exerting influence on adjacent elements akin to an invisible limb attached to a human body. Although functional, this invisible component escapes rendering by GPU or relevant graphics processing units.
  • Opacity - Comparable to visibility but offering enhanced manageability. An opacity value of 1 (or 100%) renders the element fully visible, whereas 0 translates to absolute transparency, effectively concealing the element from view. Intermediate values such as .5 or 50% ensure partial visibility allowing objects positioned behind to be partially discernible through the transparent element. Consequently, the GPU continues rendering the element whilst accommodating varying levels of transparency indicated by the opacity setting.
  • Display - Responsible for dictating an element's behavioral traits within the layout and governing its interaction with neighboring elements. Common applications encompass styles such as “display: none” that seemingly erase the element from visual display without altering its underlying HTML existence. As a result, the element remains inert concerning any impact on surrounding elements.

Moreover, grasping the intricacies associated with these attributes assumes added significance. In your scenario, dedicating attention towards transitions proves fundamental. By incorporating the transition property, one can modify how browsers handle alterations in element attributes thereby facilitating the creation of diverse effects like fades, movements, etc., all delivered seamlessly if executed adeptly.

Importantly, transformations directly affecting mentioned attributes occur instantaneously prompting the necessity for transition effects to instill fluidity into these modifications. However, such transitions solely manifest upon pre-existing attribute adjustments. For instance:

.MyDivClass{
    height: 32px;
    width: 32px;
    transition: all .3s ease;
}

.MyDivClassExtra{
    height: 64px;
    width: 64px;
}

The div expands gradually over a duration of 0.3 seconds due to predefined width and height parameters. Should such attributes remain undefined or set at auto, instantaneous transitions transpire owing to the absence of pertinent attribute data necessary for manipulation. Even configuring dimensions to zero engenders a perceptible effect given the presence of adjustable attributes.

In programming contexts, occasional suspension of conventional logic manifests, particularly concerning attributes like Visibility where anticipating gradual visual alterations despite toggling its state via transitions leads to erroneous assumptions. Conversely, Opacity introduces nuanced gradations enabling seamless transitions ranging from complete invisibility (at 0%) to full visibility (at 100%). Analogously, Display introduces binary behavior denoting mere existence or absence within the document structure, albeit slightly convoluted compared to previous attributes.

A notable discrepancy evident in your code pertains to the .modelstate overlay obstructing user interaction across the interface. Implementing visibility:hidden does not render elements unresponsive; rather, they retain influence albeit veiled from direct sight – continuing to exert control over surrounding components.

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

A step-by-step guide on smoothly transitioning between elements using Vue-Carousel on a click event

Today marks my first question here and I'm excited! Can anyone guide me on how to implement sliding on click element with Vue-Carousel? I want to slide to the right with just a single click on my input button. Here's the code snippet I have base ...

Trouble with updating data in Angular 8 table

In Angular 8, I have created a table using angular material and AWS Lambda as the backend. The table includes a multi-select dropdown where users can choose values and click on a "Generate" button to add a new row with a timestamp and selected values displ ...

What is the best way to animate the preprending of a div in an AJAX response?

Here is the code I am currently working with: $.ajax({ type: 'POST', url: 'load_more.php', data: {val:myval}, success: function (data) { $("#load_current").prepend(data); ...

Infinite error loop during start-up in AngularJS application due to digest cycle overflow

Just starting out with Angular and working on a new project using node, jade, and angular. I'm having trouble implementing a catch-all server route. Every time the index page loads, it gets stuck in a loop and crashes the app. I've tried several ...

Troubleshooting: Why Isn't Jquery Hide/Show Function

I am currently working on enhancing my Jquery skills to toggle text visibility, but I am facing some issues. I am certain that it's something quite simple. Below is the HTML code I am working with: <script src="js/showhide.js"></script> ...

Multer is successfully retrieving images, but unfortunately, it is failing to save the files in the intended directory

I am currently facing an issue with my Express server. The problem arises when a user attempts to make a post request for their profile, including a profile picture submission. I have set up Multer to handle the image upload process and store the photo in ...

What is the best way to refresh the content of an iframe when a link within the iframe is clicked?

In the code below, I am resizing the iframe based on its content: <html> <head> <title></title> </head> <body> <iframe src="http://page.html" id="iframeid" width="600" height="700" scrolling="n ...

Using an Array as an Argument in a JavaScript Function

Currently, I am utilizing a web service to populate a selection list. Now, I need to repeat this process for multiple selection lists, with the goal of minimizing the amount of code duplication. Below is the function I am using to make the web service call ...

The testPattern provided is not valid for configuration with Jest using react-scripts in a Mono Repo environment

I have been attempting to customize the jest.config for react-scripts using this configuration: "test": "react-scripts test -- --config=jest.config.js", Just wanted to point out that I am working with a mono repo. However, this setup ...

What is the best way to create a universal root component in next.js for sending requests, no matter the page URL?

Currently, my goal is to send a request to the server whenever the page is refreshed or opened in a new tab. For instance, after hitting F5, I want to trigger a request. However, I do not want to make a request after every routing event. Essentially, upon ...

What would cause the Uncaught TypeError: Unable to resolve module specifier "firebase"? Isn't it true that relative references should begin with "/ ", "./ ", or "../ "?

After transitioning my code from v8 to v9 with a modular approach, I encountered an error despite having the rollup package installed. Below is my JavaScript Code: <script type="module"> // Necessary Firebase SDKs // https://fir ...

Issues with refreshing Datatables functionality

I’ve hit a roadblock while troubleshooting this issue, and it’s gotten quite frustrating. That's why I've turned to Stackoverflow for help once again. As a beginner, I ask for your patience and thank you in advance for any assistance. In my ...

Finding the position of a currently selected div by utilizing their data attributes

I am seeking to determine the index of an active div based on its data attributes. Currently, my approach involves obtaining the index on a sorted table. However, this method is ineffective in the case of an unsorted table: var count = $(".active").index ...

Customize the behavior of the focus-visible feature on input elements

In my design, I want to remove the outline ring on an input element when it's focused via mouse interaction but still keep it visible when focused using the keyboard. This similar question was raised about a week ago here, unfortunately with no solut ...

I am seeking the original XML element with the exact tagName, including proper case sensitivity

Below is a code snippet that retrieves and displays the UpperCase text of tagNames. I am looking to work with the original case. var xml = '<myElements type="AA" coID="A923"><myHouse>01</myHouse> <myCars>02</myCars><m ...

Error message: "In Jade and Express.js, the attribute req.body.[name of form] is not defined

I am encountering an issue while trying to update a database using a drop-down form. The problem is that req.body.[name of form] is coming up as undefined. Upon checking the console, I found that req.body shows up as an empty object {}. Below is the code ...

Display an array comprising of other arrays

function PersonXYZ(fName, lName) { this.lastName = lName; this.firstName = fName; this.grades = []; this.grades.push([4, 67, 5]); this.grades.push([41, 63, 5]); this.grades.push([4, 67, 55]); } var person = new PersonXYZ('John', 'Doe&apos ...

Fade in each input box using jQuery's `.each()` method

Is it possible to fade in multiple input boxes based on a given number? For example, if the number entered is 5, I would like to fade in 5 input boxes. Can someone assist with achieving this? $('.submit').click(function(){ var num = $(&apos ...

Why is it necessary to execute all tasks in JavaScript within functions that are invoked by the HTML?

I often find it frustrating that global variables cannot be easily defined, and it's a bit of a nuisance. I wonder why the code outside functions that are called doesn't execute? For instance, if I trigger the myFunction function from HTML, this ...

Adjust the height and width dynamically in CSS/HTML based on various screen dimensions

There are 2 major concerns I have regarding this layout : .feature_content (with a grey background) does not adjust its height and width to different screen sizes. Currently, on large screens, .feature_content is positioned far from the footer. There is ...