What is the best way to incorporate multiple modals onto a website?

Currently, I am immersed in the world of blog designing and facing a challenge with creating multiple modals. It is my strong belief that Modals should be clearly defined in Javascript.

// Accessing the modal element
var modal = document.getElementById('myModal');

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

// Accessing the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// Opening the modal when the user clicks the button 
btn.onclick = function() {
    modal.style.display = "block";
}

// Closing the modal when the user clicks on <span> (x)
span.onclick = function() {
    modal.style.display = "none";
}

// Closing the modal when the user clicks anywhere outside of it
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}
/* The Modal (background) */
.modal {
  display: none;
  /* Default hidden state */
  position: fixed;
  /* Staying in place */
  z-index: 1;
  padding-top: 100px;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgb(0, 0, 0);
  background-color: rgba(0, 0, 0, 0.4);
}
/* Styling for Modal Content */

.modal-content {
  position: relative;
  background-color: #fefefe;
  margin: auto;
  padding: 0;
  border: 1px solid #888;
  width: 80%;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
  -webkit-animation-name: animatetop;
  -webkit-animation-duration: 0.4s;
  animation-name: animatetop;
  animation-duration: 0.4s
}
/* Adding Animation */

@-webkit-keyframes animatetop {
  from {
    top: -300px;
    opacity: 0
  }
  to {
    top: 0;
    opacity: 1
  }
}
@keyframes animatetop {
  from {
    top: -300px;
    opacity: 0
  }
  to {
    top: 0;
    opacity: 1
  }
}
/* Style for Close Button */

.close {
  color: white;
  float: right;
  font-size: 28px;
  font-weight: bold;
}
.close:hover,
.close:focus {
  color: #000;
  text-decoration: none;
  cursor: pointer;
}
.modal-header {
  padding: 2px 16px;
  background-color: #5cb85c;
  color: white;
}
.modal-body {
  padding: 2px 16px;
}
.modal-footer {
  padding: 2px 16px;
  background-color: #5cb85c;
  color: white;
}
<h2>Animated Modal with Header and Footer</h2>
<button id="myBtn">Open Modal</button>
<div id="myModal" class="modal">
  <div class="modal-content">
    <div class="modal-header">
      <span class="close">&times;</span>
      <h2>Modal Header</h2>
    </div>
    <div class="modal-body">
      <p>Some text in the Modal Body</p>
      <p>Some other text...</p>
    </div>
    <div class="modal-footer">
      <h3>Modal Footer</h3>
    </div>
  </div>
</div>

Answer №1

If you're utilizing jQuery, a simple way to achieve this is by using general classes like:

<button class="myBtn">Open Modal 1</button>

<div class="modal">
  <div class="modal-content">
    <div class="modal-header">
      <span class="close">&times;</span>
      <h2>Modal Header 1</h2>
    </div>
    <div class="modal-body">
      <p>Some text in the Modal Body 1</p>
      <p>Some other text...</p>
    </div>
    <div class="modal-footer">
      <h3>Modal Footer 1</h3>
    </div>
  </div>
</div>

JavaScript :

$('.myBtn').on('click', function(){
  $(this).next('.modal').show();
})

$('.close').on('click', function(){
  $(this).closest('.modal').hide();
})

Hope this explanation assists you.

$('.myBtn').on('click', function(){
  $(this).next('.modal').show();
})

$('.close').on('click', function(){
  $(this).closest('.modal').hide();
})
.modal {
    display: none; /* Initially hidden */
    position: fixed; /* Positioned accordingly */
    z-index: 1; /* On top */
    padding-top: 100px; /* Positioning of the box */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scroll if necessary */
    background-color: rgb(0,0,0); /* Fallback color */
    background-color: rgba(0,0,0,0.4); /* Black with opacity */
}

/* Styling for Modal Content */
.modal-content {
    position: relative;
    background-color: #fefefe;
    margin: auto;
    padding: 0;
    border: 1px solid #888;
    width: 80%;
    box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19);
    -webkit-animation-name: animatetop;
    -webkit-animation-duration: 0.4s;
    animation-name: animatetop;
    animation-duration: 0.4s
}

/* Animation Effects */
@-webkit-keyframes animatetop {
    from {top:-300px; opacity:0} 
    to {top:0; opacity:1}
}

@keyframes animatetop {
    from {top:-300px; opacity:0}
    to {top:0; opacity:1}
}

/* Close Button styling */
.close {
    color: white;
    float: right;
    font-size: 28px;
    font-weight: bold;
}

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

.modal-header {
    padding: 2px 16px;
    background-color: #5cb85c;
    color: white;
}

.modal-body {padding: 2px 16px;}

.modal-footer {
    padding: 2px 16px;
    background-color: #5cb85c;
    color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Animated Modal with Header and Footer</h2>

<!-- Trigger/Open The Modal 1-->
<button class="myBtn">Open Modal 1</button>

<!-- The Modal -->
<div class="modal">

  <!-- Modal content -->
  <div class="modal-content">
    <div class="modal-header">
      <span class="close">&times;</span>
      <h2>Modal Header 1</h2>
    </div>
    <div class="modal-body">
      <p>Some text in the Modal Body 1</p>
      <p>Some other text...</p>
    </div>
    <div class="modal-footer">
      <h3>Modal Footer 1</h3>
    </div>
  </div>

</div>

<!-- Trigger/Open The Modal 2 -->
<button class="myBtn">Open Modal 2</button>

<div class="modal">

  <!-- Modal content -->
  <div class="modal-content">
    <div class="modal-header">
      <span class="close">&times;</span>
      <h2>Modal Header 2</h2>
    </div>
    <div class="modal-body">
      <p>Some text in the Modal Body 2</p>
      <p>Some other text...</p>
    </div>
    <div class="modal-footer">
      <h3>Modal Footer 2</h3>
    </div>
  </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

Ways to update or migrate the schema of a remote client's standalone database when performing updates

Situation: Currently, I am developing a desktop-based application that requires management of multiple independent production sites. Each site has its own server, database, and local clients. The software gets automated updates regularly, which includes s ...

When using next.js, a warning may be encountered that states: "A value of NaN was received for the `children` attribute. To resolve this, ensure the value is cast as

I am currently tackling my first Next.js project and have created a file called myCart.js. Below is the code snippet: function orderCard(arr1) { //Code here... } let noRefresh; function makeGetRequest() { //Code here... } export default makeGetReques ...

Toggle a v-if variable within the created() lifecycle hook in the VUE 3 framework

I'm working on a component with 3 buttons, where initially only 2 are visible. <template> <button v-show="!showLogout" @click="login('google', 'profile, email')"> Google </button> &l ...

Error: The function $(...).froalaEditor is not recognized | This issue is occurring within the $(document).ready(function(){}) block in J

When attempting to set HTML content of the Froala editor within a JSP using $(document).ready(), this error occurs. TypeError: $(...).froalaEditor is not a function | $(document).ready(function(){}) in JSP I read on a GitHub issue that placing jQuery sc ...

AngularJS and Bootstrap tabs clashing with each other

I have implemented the JavaScript Bootstrap 3 tabs according to the documentation, as shown below: <!-- Nav tabs --> <ul class="nav nav-tabs" role="tablist"> <li class="active"><a href="#home" role="tab" data-toggle="tab">Home< ...

Learn how to connect a Firebase account that was created using a phone number

✅ I have successfully implemented the feature that allows users to update their profile with a mobile number using verifyPhoneNumber and update currentUser.updatePhoneNumber ❌ However, a problem arises when a new user attempts to sign in with a phone ...

retrieving the value stored in a concealed input field

I am facing an issue with the following code snippet: <div id = "askpost" class="row"> <input type="hidden" name="askid" id="askid" value="<?php echo $askpostid ?>"> </div> My goal is to retrieve the ID of the hidden input element ...

Struggling to resolve a common issue in Migration? It seems that a raw query in Sequelize is adding backslashes that are causing errors when inserting values into the database

During migration, data is taken from one table and inserted into another. However, an issue arises when Sequelize adds backslash escape characters to the 'v_occupation' value, causing insertion errors. I have attempted various replacements and m ...

Angular encounters issue when retrieving CSS file while navigating to a nested route

When trying to access a child component directly in production mode (using ng serve --prod), it fails to load the CSS file as it attempts to fetch it from a nested path. For example, when navigating to "localhost:4200/doc/", the CSS Request URL is: loca ...

Find the matching ID and consolidate all the information under one single ID

I am looking to merge objects with the same title and consolidate their data into a single object. new = [{ "data": [{ "displayName": "Peter pvt ltd", "name": "Peter Zon"}], "title&quo ...

Alter the HTML content prior to the templating process

Utilizing the Mustache template script for rendering my JSON values has been helpful. One thing that I've been pondering is whether it's possible to apply .data() to the object before rendering it into the HTML. To provide a clearer example, co ...

Variability in the positioning of list item markers depending on the child's display property

Looking at this code: <ul> <li> <div id="container"> <button>toggle display</button> <div>text</div> <div>text</div> </div> </li> ...

Show a notification when the values of variables 'enter' are not the

I have a website featuring 2 text boxes, a button, and a paragraph. What I would like to do is have users input a number into textbox1, another number into textbox2, and then click the "calculate" button. Upon doing so, a statement should appear indicating ...

Find all child elements in Jquery that meet a specific condition

Within my HTML document, I have a div element with the id='tips'. This particular div contains multiple child elements. My objective is to retrieve a specific child of the div with the id='tips' that has its style attribute set to top & ...

Issue with memory leak in Three.js r89 when using STL models

I'm struggling with a webpage I'm constructing. It seems like a simple task, but I keep encountering issues that I suspect may be caused by a memory leak. Despite spending most of the day researching for a solution, I can't seem to find one ...

What is the process for clicking a button in Selenium Python that lacks a "select" tag and only becomes clickable after fulfilling certain conditions?

Currently, I am working on automating the process of downloading files. To locate these files, I need to interact with two dropdown menus: one named 'Select Period' where I choose a date, and the other named 'Select File Type' where I s ...

JavaScript API for Facebook

I've been attempting to retrieve my status from Facebook using the JavaScript API. Below is the code I have been using: <div id="fb-root"></div> <div id="data"></div> <script src="http://connect.facebook.net/en_US/all.j ...

"Using jQuery's each method on an array can retrieve items that are not present

I am currently working on a dropdown list of categories that have specific id's and names associated with them. My main goal with this jQuery script is to loop through the category id's in the list. If it doesn't find the category id, I wan ...

An AngularJS project utilizing exclusively EJB

Can an AngularJS application be built directly with EJB without needing to expose them as REST services? Many examples on the internet show that eventually REST services are required to provide data to AngularJS. This means that EJB methods must be expos ...

A full month displayed on the highcharts x-axis

I've created a graph, but I'm struggling to display all 31 days of the month on the x-axis. You can view the current setup here. However, the 31st day is missing. Here's the modified code: Updated code here. How do I ensure that the 31st ...