JavaScript: Pop-up form fades in from the top

I have successfully built a Modal form using only Javascript and Css. The animation effects in Bootstrap's modal, such as the card appearing FadeInDown and fading out with FadeInUp, caught my attention. I would like to implement similar animations within my application. So far, I have created an animation called FadeIn, but I am unsure how to integrate this logic into Javascript. I have shared snippets of my code below and would greatly appreciate any guidance on incorporating the animation in javascript.

const modal = document.getElementById("myModal");
const btn = document.getElementById("myBtn");
const span = document.getElementsByClassName("close")[0];

btn.onclick = function () {
  modal.style.display = "block";
}

span.onclick = function () {
  modal.style.display = "none";
}

document.body.addEventListener('click', function (event) {
  if (event.target === modal) {
    modal.style.display = "none";
  }
})
  .modal {
    display: none;
    position: fixed;
    z-index: 10;
    padding-top: 100px;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    overflow: auto;
    opacity: 0;
    background-color: rgba(0,0,0,0.5);
  }

  /* Modal Content */
  .modal-content {
    background-color: #fefefe;
    margin: auto;
    padding: 20px;
    border: 1px solid #888;
    width: 50%;
    height: 80%;
    border-radius: 5px;
    box-shadow: 0 24px 38px 3px rgba(60,75,100,.14);
  }

  .close {
    color: #aaaaaa;
    float: right;
    font-size: 28px;
    font-weight: bold;
  }

  .close:hover,
  .close:focus {
    color: #000;
    text-decoration: none;
    cursor: pointer;
  }

/* animation*/
.fade{
  animation: fadeIn .1s ease-in .5s both;
}

@keyframes fadeIn {
  0% {
      opacity: 0;
  }
  100% {
      opacity: 1;
  }
}
  <button id="myBtn">Open Modal</button>
  <div id="myModal" class="modal fade">
    <div class="modal-content">
      <span class="close">&times;</span>
        <form action="submit">
          <label for="name">Name:</label>
          <input type="text" id="fname" name="fname"><br><br>
          <label for="email">email:</label>
          <input type="text" id="email" name="email"><br><br>
          <label for="Telephone">Telephone</label>
          <input type="number" id="telephone" name="telephone"><br><br>
          <label for="description">Description:</label>
          <input type="text" id="description" name="description"><br><br>
          <input type="submit" value="submit">
        </form>
    </div>
  </div>

Answer №1

To enhance your modal functionality, consider creating a new class called .visible and implementing transitions for transform and opacity properties.

const modal = document.getElementById("myModal");
  const btn = document.getElementById("myBtn");
  const span = document.getElementsByClassName("close")[0];

  btn.onclick = function () {
    modal.classList.add("visible");
  };

  span.onclick = function () {
    modal.classList.remove("visible");
  };

  document.body.addEventListener("click", function (event) {
    if (event.target === modal) {
      modal.classList.remove("visible");
    }
  });
        .modal {
    position: fixed;
    z-index: 10;
    padding-top: 100px;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    overflow: auto;
    background-color: rgba(0, 0, 0, 0.5);
    transform: translateY(-100%);
  }

  /* Modal Content */
  .modal-content {
    background-color: #fefefe;
    margin: auto;
    padding: 20px;
    border: 1px solid #888;
    width: 50%;
    height: 80%;
    border-radius: 5px;
    box-shadow: 0 24px 38px 3px rgba(60, 75, 100, 0.14);
    opacity: 0;
    transform: translateY(-100%);
    transition: 0.75s ease;
    transition-property: opacity, transform;
  }

  .close {
    color: #aaaaaa;
    float: right;
    font-size: 28px;
    font-weight: bold;
  }

  .close:hover,
  .close:focus {
    color: #000;
    text-decoration: none;
    cursor: pointer;
  }

  .visible {
    transform: translateY(0%);
  }

  .visible > .modal-content {
    transform: translateY(0%);
    opacity: 1;
  }
  <button id="myBtn">Open Modal</button>
  <div id="myModal" class="modal fade">
    <div class="modal-content">
      <span class="close">&times;</span>
        <form action="submit">
          <label for="name">Name:</label>
          <input type="text" id="fname" name="fname"><br><br>
          <label for="email">email:</label>
          <input type="text" id="email" name="email"><br><br>
          <label for="Telephone">Telephone</label>
          <input type="number" id="telephone" name="telephone"><br><br>
          <label for="description">Description:</label>
          <input type="text" id="description" name="description"><br><br>
          <input type="submit" value="submit">
        </form>
    </div>
  </div>

Another recommendation is to utilize the aria-hidden attribute by setting it to true when the modal is closed and false when open. This will improve accessibility by preventing screen readers from reading the hidden markup while the modal is closed.

Answer №2

In order to achieve this effect, we will start by moving the .modal-content element up by -40px initially. When the modal is opened, after a brief delay, we will move it back to its original position. This animation can also be applied when closing the modal.

  1. Add the following CSS properties to .modal-content: opacity: 0; and transform: translateY(-40px);

  2. Create a new rule:

    .modal-content.active{
         opacity: 1;
         transform: translateY(0);
    }
    
  3. Define a variable named modal_content:

    const modal_content = document.getElementsByClassName("modal-content");
    
  4. Add the active class to .modal-content on btn.click with a delay:

    setTimeout(() => {
        modal_content[0].classList.add("active");
    }, 500)
    
  5. Remove the active class when the close button is clicked:

    modal_content[0].classList.remove("active");
    

const modal = document.getElementById("myModal");
const modal_content = document.getElementsByClassName("modal-content");

const btn = document.getElementById("myBtn");
const span = document.getElementsByClassName("close")[0];

btn.onclick = function () {
  modal.style.display = "block";
  setTimeout(() => {
    modal_content[0].classList.add("active");
  }, 500)
}

span.onclick = function () {
  modal_content[0].classList.remove("active");
  setTimeout(() => {
      modal.style.display = "none";
  }, 500)
}

document.body.addEventListener('click', function (event) {
  if (event.target === modal) {
    modal_content[0].classList.remove("active");
    setTimeout(() => {
      modal.style.display = "none";
    }, 500)
  }
})
.modal {
    display: none;
    position: fixed;
    z-index: 10;
    padding-top: 100px;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    overflow: auto;
    opacity: 0;
    background-color: rgba(0,0,0,0.5);
  }

.modal-content.active{
  transform: translateY(0);
  opacity: 1;
}
.modal-content {
    background-color: #fefefe;
    margin: auto;
    padding: 20px;
    border: 1px solid #888;
    width: 50%;
    height: 80%;
    border-radius: 5px;
    box-shadow: 0 24px 38px 3px rgba(60,75,100,.14);
    transform: translateY(-40px);
    opacity:0;
    transition: 0.4s;
}

.close {
    color: #aaaaaa;
    float: right;
    font-size: 28px;
    font-weight: bold;
}

.close:hover,
.close:focus {
    color: #000;
    text-decoration: none;
    cursor: pointer;
}


.fade{
  animation: fadeIn .1s ease-in .5s both;
}

@keyframes fadeIn {
  0% {
      opacity: 0;
  }
  100% {
      opacity: 1;
  }
}
<button id="myBtn">Open Modal</button>
  <div id="myModal" class="modal fade">
    <div class="modal-content">
      <span class="close">&times;</span>
        <form action="submit">
          <label for="name">Name:</label>
          <input type="text" id="fname" name="fname"><br><br>
          <label for="email">Email:</label>
          <input type="text" id="email" name="email"><br><br>
          <label for="Telephone">Telephone</label>
          <input type="number" id="telephone" name="telephone"><br><br>
          <label for="description">Description:</label>
          <input type="text" id="description" name="description"><br><br>
          <input type="submit" value="Submit">
        </form>
    </div>
  </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

Unexpected error in JavaScript, Curl, and Node interactions

After sending some JSON to a Node server using CURL, I faced an unexpected issue. Even though the data was received successfully and printed using console.log(...), attempting to run JSON.parse(...) resulted in an error: undefined:1 '{command:print ...

The combination of Grunt and Babel runs smoothly, but fails to produce any results

I'm fairly new to the world of grunt and npm. After diving into the documentation, I managed to create my own package.json and a Gruntfile.js. This is how my directory structure looks: / |- src |- myfile.es6 |- anotherfile.es6 |- etc. |- ...

Using Slim Framework and AJAX to handle the forward slash character as a parameter

I am using an ajax call to communicate with a web service built on the Slim framework. This service is responsible for storing notes in my database. One issue I am facing is that users are allowed to input strings like "send 1/2 piece". This causes a prob ...

The image is not displaying on the button

When using 3 buttons in my extjs script, I noticed a strange issue where the buttons were not visible on the page. Upon inspecting the elements using firebug, here is what I found: <button id="button-1051-btnEl" class="x-btn-center" autocomplete="off" ...

Positioning items in a CSS grid layout involves ensuring that item 1 remains at the bottom of its column, while item 2 is centered within its column

I am trying to create a grid layout using CSS grid: The main section should have two columns. The first column will contain an image that sticks to the bottom of the grid, while the second column will display a centered card. Below are my HTML/CSS codes: ...

Accessing JSON data in a Node.js application using a GET request

Extracting the Indication value from the following data set is what I need help with. { "records": [{ "id": "recBgV3VDiJeMkcwo", "fields": { "DrugName": "azatadine", "nameapi": ["recBgV3VDiJeMkcwo"], ...

Is there a way to verify the presence of a string that matches a regex in an array using JavaScript?

My objective is to generate an array containing non-duplicate lines starting from the end of one array to the beginning of another array. Here is what I attempted: for(var i = len; i > 0; i--){ if(resultArray[i] != undefined && resultA ...

Potential security concern with Java interpreting JavaScript on the server side

Is there a security risk in evaluating Javascript code submitted from the browser on a server (Java webapp using Rhino Javascript Engine)? The purpose of evaluating the JavaScript is simply to determine its validity. No results are expected from the eval ...

In JavaScript, merging objects will exclusively result in an identifier being returned

When working with mongoose, I have encountered an issue where combining data from multiple finds only displays the id instead of the entire object. Interestingly, when I use console.log() on the object directly, it shows all the contents. Below are snippe ...

Combining Bootstrap Vue: utilizing class names alongside HTML tags

(Bootstrap-Vue 2.0, Vue.js 2.5) Is it possible to combine traditional CSS Bootstrap 4 classes with Bootstrap-Vue? For example, can I use the following code snippet: <section id="introduction"> <b-container class="h-100"> & ...

Leveraging Google Sheets as a Dynamic Database with Ajax

I found a helpful guide on using Google Sheets as a database with Apps Script and ajax. Here is the link. I understand that I need to include 'Google Sheet/Apps Script Code' in a spreadsheet. However, I'm unsure about what needs to be place ...

Utilize try-catch or async-await within useEffect when testing with Jest

I am currently setting up my initial unit tests using JEST. I've installed Jest Fetch Mock but unfortunately, I keep encountering an error stating "The promise rejected with reason FetchError". After doing some research, it seems like I may need to i ...

Styling the <td> elements within a table using Bootstrap-Vue

Help needed: Applying styles to the <td> tag of a b-table element. Check out this template: <b-table :fields="fields" :items="items" class="mx-1 mt-2" v-if="items && items.length > 0" > <tem ...

Begin with a Bootstrap non-fluid container and follow with a fluid container

I am currently facing a challenge where I want the lower section of my webpage to be full width within a container-fluid div, while keeping the top part in a traditional container with a set width. Despite my efforts, the following HTML snippet is not ach ...

JavaScript Equivalent of Declaration in TypeScript

In my Next JS application, I encountered a situation where a line of code relies on a variable from a script src in the app.tsx page. Here's how it looks: app.tsx: <script src="https://js.stripe.com/v3/"></script> config.ts: de ...

Issue with Adding Additional Property to react-leaflet Marker Component in TypeScript

I'm attempting to include an extra property count in the Marker component provided by react-leaflet. Unfortunately, we're encountering an error. Type '{ children: Element; position: [number, number]; key: number; count: number; }' is n ...

Converting Xpath into a CSS selector

Having a difficult time converting the Xpath "//form[@id='giftcard-form']/div[3]/div/button" to CSS. I've tried using it for my Selenium JS but it's not working for some reason. Managed to convert an easier one successfully and use it i ...

The bootstrap navbar-collapse feature is causing a shift in the orientation of the navigation elements

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="navbar navbar-default" role="nav ...

The modal in NextJs with parallel routes does not close when navigating to a different page

I recently implemented Nextjs parallel routes for my project and everything was working smoothly until I encountered an issue with linking it to a server action that deletes the post displayed in a modal and redirects to the home page. My project is using ...

Tips for making a div expand to take up the available space on the left side of a taller div

Could you take a look at the scenario below? I'm attempting to position my yellow div beneath the red div and on the left side of the lower part of the green div. When I apply clear: left, it moves down but leaves empty space above it. Is there a way ...