Instructions on how to access multiple modals on a single page

I am struggling to make two buttons open one modal and two other buttons open a different modal. Can you please help me figure out why the second modal keeps opening instead of the one I want? Each button has a unique ID generated from a MySQL database, and I want it to correspond to a specific modal popup. I have looked at various resources online but haven't been able to tailor the solutions to my specific requirements. Also, I prefer not to use Bootstrap for this.

Answer №1

It seems like the issue lies in how you're handling the variable names modal, btns, and span. One way to address this is by renaming those variables, but an even better approach would be to optimize your code for efficiency.

To solve the problem, I modified the id of the first modal by adding a suffix of #1. This way, we can easily link the button's id to the corresponding modal.

I've added comments throughout the code for clarity:

// Get all buttons with the class 'pack.detail'
var btns = document.querySelectorAll('.pack.detail');
// Get all the close spans
var span = document.querySelectorAll('span.close');

// Using original forEach loop
[].forEach.call(btns, function(el) {
  el.onclick = function() {
    // Retrieve the button's id
    var id = el.id;
    // Find the modal based on id
    var modal = document.getElementById('modal' + id);
    // Display the correct modal
    modal.style.display = "block";
  }
});

// Handle clicks on close spans
[].forEach.call(span, function(el) {
  el.onclick = function() {
    // Find the closest parent element with class 'modal'
    var current_modal = el.closest('.modal');
    // Hide the modal
    current_modal.style.display = "none";
  }
});

// Close modal on window click if target has class 'modal'
window.onclick = function(event) {
  if (event.target.className == 'modal') {
    event.target.style.display = "none";
  }
}
/* Modal styling */

.modal {
  display: none;
  position: fixed;
  z-index: 1;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgb(0, 0, 0);
  background-color: rgba(0, 0, 0, 0.4);
  -webkit-animation-name: fadeIn;
  -webkit-animation-duration: 0.4s;
  animation-name: fadeIn;
  animation-duration: 0.4s
}

/* Content styling */
.modal-content {
  position: fixed;
  bottom: 0;
  background-color: #fefefe;
  width: 100%;
  -webkit-animation-name: slideIn;
  -webkit-animation-duration: 0.4s;
  animation-name: slideIn;
  animation-duration: 0.4s
}

/* 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;
}
<button class="pack detail" id="1">Open modal 1</button>
<button class="pack detail" id="2">Open modal 2</button>

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

<!-- Modal 2 -->
<div id="modal2" class="modal">
  <div class="modal-content">
    <!-- Header -->
    <div class="modal-header">
      <span class="close">&times</span>
      <h2>Modal Header2</h2>
    </div>
    <!-- Body -->
    <div class="modal-body">
      <p>Some text in the Modal Body2</p>
      <p>Some other text...</p>
    </div>
    <!-- Footer -->
    <div class="modal-footer">
      <h3>Modal Footer2</h3>
    </div>
  </div>
</div>

Answer №2

To prevent code duplication, it's important to incorporate dynamic elements when dealing with button ids obtained from a database. Each button's id should correspond to the modal it is intended to trigger.

Custom HTML Structure

<button class="pack detail" id="1">Open modal 1</button>
<button class="pack detail" id="2">Open modal 2</button>

<!-- First Modal -->
<div id="modal1" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <span class="close" data-modal='modal1'>&times</span>
            <h2>Modal Header</h2>
        </div>
        
        <div class="modal-body">
            <p>Text within the Modal Body</p>
            <p>Additional text...</p>
        </div>
       
        <div class="modal-footer">
            <h3>Modal Footer</h3>
        </div>
    </div>
</div>

<!-- Second Modal -->
<div id="modal2" class="modal">
    <div class="modal-content">
       <div class="modal-header">
            <span class="close" data-modal='modal2'>&times</span>
            <h2>Header for Modal2</h2>
        </div>

        <div class="modal-body">
            <p>Some text in Modal Body2</p>
            <p>Another piece of text...</p>
        </div>

        <div class="modal-footer">
            <h3>Footer for Modal2</h3>
        </div>
    </div>
</div>

Javascript Functionality

var btns = document.querySelectorAll('.pack.detail');
var spans = document.querySelectorAll(".close");

btns.forEach(function(el) {
  el.onclick = function() {
    var id = el.id;
    var modal = document.getElementById('modal' + id);

    alert(id);
    modal.style.display = "block";
  }
})

spans.forEach(function(span) {
  span.onclick = function(event) {
    var modal = document.getElementById(event.target.dataset.modal);
    modal.style.display = "none";    
  }
})

window.onclick = function(event) {
    var modal = document.querySelector('.modal');

    if (event.target == modal) {
        modal.style.display = "none";
    }
}

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

Inconsistent performance: Twitter Bootstrap navigation functions flawlessly on desktop but encounters issues on

I have been using the collapsing navigation menu from Twitter Bootstrap for my website as shown in this demo: While it works perfectly fine on desktop browsers when I resize the window, it doesn't seem to work on my mobile device (iPhone 4s). The Bo ...

Manage form submission seamlessly without redirecting. Capture information without needing to prevent the default action, then proceed with redirection. Avoid redirecting when using preventDefault, but be aware that data may not

Currently stuck in a tricky situation. I've implemented a custom form submission to prevent redirecting when an express route is triggered by form submission. However, the issue arises when I lose the data being sent without redirection. document.get ...

What is the best way to center a menu for a cohesive and balanced appearance?

I am encountering an issue with my design. I am attempting to center-align a menu, but I want it to appear uniform and consistent. I want it to resemble the layout shown in the image link below. https://i.sstatic.net/D3Rep.png I cannot understand why my ...

Can you explain the distinction between sockets and proxy passing in nginx compared to uwsgi?

My latest project setup involves flask, uwsgi, and nginx. The backend solely serves json data through an API, while the client side takes care of rendering. Typically, my Nginx configuration looks like this: My usual setup (with basic proxy passing): se ...

JS will reach its stopping point at the specified style.zIndex

I am currently in the process of setting up button elements. I have two scripts that correspond to different types of buttons - one script runs a simple collapse menu, while the other executes a more complex collapse by shifting depths and sliding one div ...

Adjusting images of various sizes within a single row to fit accordingly

I am faced with a challenge of aligning a set of images on a webpage, each with varying heights, widths, and aspect ratios. My goal is to arrange them in a way that they fit seamlessly across the screen while ensuring their heights are uniform. Adjusting ...

Customize the appearance of the search box in Serverside Datatables

Is there a way to adjust the search and show inputs for datatables so that I can customize their width and make them fit my dynamic column sizing? The issue I ran into is that these inputs are enclosed within <label> tags in the source JavaScript, an ...

Is there a way to block the .load() function directly from the browser console?

I am looking to enhance the user experience on my website by dynamically loading certain content after login. This involves using a $.post(...) method to interact with a servlet that verifies the user's credentials, followed by a $.load(url) function ...

Is it possible to position my label above my text box input?

Having trouble aligning the checkbox label with the edge of the text area in my login form code. It always ends up on the right side, outside of the div container when inspected. I've attempted setting a left value for the label, but it causes issues ...

Listening to audio on a mobile browser using an HTML audio element

What is the solution for the problem of playing audio on a mobile browser when it plays on a desktop browser but not on mobile? The code being used is: var audio = new Audio('sound.mp4') audio.play() ...

Examining the words within strings and drawing comparisons

I am attempting to analyze words within strings for comparison purposes. This is my objective: var string1 = "Action, Adventure, Comedy"; var string2 = "Action Horror"; if (string1 contains a word from string 2 == true) { alert("found!"); } I have e ...

Activate just the show more / show less button on the website that has several buttons with identical ids

Whenever the "show more" button is clicked, additional images are displayed in the gallery and the button text changes to "show less". However, in my ExpressionEngine (CMS) templates and entries, all "show more" buttons share the same id, causing other but ...

Extracting textual information from Wikipedia through iframes?

Currently, I am working on a website project utilizing Squarespace. This site will feature multiple pages dedicated to individuals who have reached a level of notability worthy of having their own Wikipedia page. With over 150 pages planned, manually writi ...

Incorporating a new data series into your candlestick chart with Highstock

I've encountered an issue with adding a data series to my candlestick chart in Highstock using Highcharts. Here's the script I'm using: $.ajax({ url : 'indicator', type : 'GET', data ...

Personalized date range filter

I've been attempting to narrow down the data based on two specific dates, but I seem to be having trouble getting it to work correctly. Is there anyone out there who can lend a hand? Here is my HTML: <input type="date" ng-model="from_date"> &l ...

Question: When referencing $(this) in a different div, how can you navigate back to the previous div and access its children elements in jQuery?

Here's the code I've been working on: When a user clicks on a link with the class '.like', I want the total number of likes (found in the div.postInfo as '.PostlikeCount') to update and display the new total. $(".like").cl ...

The abbreviation for the <select> element is used in iPhone and Android web browsers

I've encountered a dilemma with my HTML <select> dropdowns when viewed in iPhone or Android browsers. The issue arises when I have to display lengthy <option> labels, like this example: [AccountType] [EUR] - [Customer] - CH12 3456 7890 ...

What could be preventing a successful POST request with data when making an ajax call?

My goal is to send data using a POST request in client-side code. However, when the request reaches the controller methods, I am unable to retrieve the sent data. Here is the client-side code snippet: function AddUser() { var user = { ...

The cursor seems to be playing a game of hopscotch every time I

In the text box, I've implemented a feature to prevent typing of a forbidden character: #. While this feature is successful in restricting the input of the forbidden character, there's an issue that arises when data is already filled in the text ...

Having trouble modifying the image source within a parent div that contains dynamic images? Let me assist you in fixing the Uncaught Syntax

As I work on customizing a WordPress site, one of the pages I am focusing on is called "Team Members". Each team member has their own parent div containing information and an image. My goal is to change the image when the mouse hovers over the parent div ...