Numerous instances of utilizing the identification feature to trigger the opening of a popup dialogue

After following this tutorial, I was able to create a pop-up box with a contact form. However, I am looking for a way to reuse this code in multiple locations without having to change the IDs for each button.

If anyone has any advice on how to achieve this, please let me know. I'm open to suggestions and willing to provide more information if needed.

You can visit my site here. I have added the ID to both slider links.

Below is the code snippet for my pop-up box and button:

<button id="myBtn" class="btn btn-light">
   click here
  </button>
    
    <div id="myModal" class="modal">
    
      <!-- Modal content -->
      <div class="modal-content">
        <span class="close">&times;</span>
        <?php echo do_shortcode('[wpforms id="439"]'); ?>
      </div>

This is the JavaScript I am using:

// Get the modal
var modal = document.getElementById("myModal");

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

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

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

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

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}

Answer №1

Greetings and thank you for your inquiry. I have provided the code below for multiple modals to work seamlessly:

// Function to open modal
function openModal(modal)
{
  var modal = document.getElementById(modal);
    modal.style.display = "block";
    var span = document.querySelector("#"+modal.id+" .close");
    span.onclick = function() {
      modal.style.display = "none";
    }
    window.onclick = function(event) {
      if (event.target == modal) {
        modal.style.display = "none";
      }
    }
}
body {font-family: Arial, Helvetica, sans-serif;}

/* Modal Styling */
.modal {
  display: none;
  position: fixed;
  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);
}

/* Content within Modal */
.modal-content {
  background-color: #fefefe;
  margin: auto;
  padding: 20px;
  border: 1px solid #888;
  width: 80%;
}

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

.close:hover,
.close:focus {
  color: #000;
  text-decoration: none;
  cursor: pointer;
}
<h2>Modal Example</h2>

<!-- Trigger/Open The Modal -->
<button onclick="openModal('modal1')">Open Modal 1</button>
<button onclick="openModal('modal2')">Open Modal 2</button>

<!-- Modal 1 -->
<div id="modal1" class="modal">
  <div class="modal-content">
    <span class="close">&times;</span>
    <p>Text inside Modal1..</p>
  </div>
</div>

<!-- Modal 2 -->
<div id="modal2" class="modal">
  <div class="modal-content">
    <span class="close">&times;</span>
    <p>Text inside Modal2..</p>
  </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

Building hierarchical comments in React Native

I'm currently involved in a React Native project that includes a Nested comment section. These comments are retrieved as JSON data and displayed using a FlatList. const App = () => { const [isLoading, setLoading] = useState(true); const [data, ...

Error: The 'address' property cannot be found in the specified 'string' type

Hey there! I'm currently facing an issue while trying to pass an object from one page to another and store it in the object on the second page. I'm encountering an error with EsLint. let accountDetails:any={ name:this.userAccount.name, p ...

Ways to trigger an npm script from a higher-level directory?

After separately creating an express-based backend (in folder A) and a react-based front-end project (in folder B), I decided to merge them, placing the front-end project inside the back-end project for several advantages: No longer do I need to manu ...

What could be the reason for the 'if' statement not being assessed in the 'then' promise of the ajax request?

I'm facing an issue with an ajax call in my code. I have a 'then' promise set up to handle errors, where the console log returns false correctly when there is an error. However, for some reason, the if condition in the next line is not being ...

Unable to get CSS Filter to function properly in Firefox

I'm having trouble with the CSS filter on my Firefox (15.0) browser. Here is the HTML code: <div class="google"> <img src="https://www.google.com/images/srpr/logo3w.png"> </div> And here is the CSS code: .google{ -moz ...

Implementing image display in autocomplete feature using jQuery

I am currently working on a project using Spring MVC, where I am implementing a jQuery autocomplete plugin to fetch data from a JSON file generated by the server. $('#searchTerm').autocomplete({ serviceUrl: '${ctx}/search/searchAutocomp ...

Breaking the link from the image it is connected to using [middleman] css and html

My question is about an icon with a link attached to it. <%= link_to image_tag("infobutton_circle_blue.png") ,"http://redbullrecords.com/artist/awolnation/", :id => "about" %> After applying styles, the link may not work properly: <a id="abo ...

Automated Facebook Wall Publishing

I have successfully integrated a feature in my application where users can post status updates, photos, and URLs on their Facebook Like stream. I have also added an option for users to post directly on Facebook by including a checkbox. When the user clicks ...

The console log is displaying 'undefined' when trying to access Node.js fs

Recently, I was engrossed in developing a Next.js blog. After completing the frontend, I shifted my focus to building the backend using Next.js. ./pages/api I created a new file: ./pages/api/blogs.js To test my backend functionalities, I generated some J ...

Exploring the method of utilizing JQuery to modify CSS classes

I'm currently working on a multi-user application with basic layouts, and I'm looking for a way to customize the layout and style of the page for each individual user. One solution I've considered is changing the CSS at runtime, but I' ...

Defining the TypeScript interface for the onClick event in ReactJS

If you're looking to dive into React development, the tutorial on reactjs.org is a great place to start. While the tutorial code is in JavaScript, I've been working on converting it to TypeScript. I've successfully translated most of the c ...

What can I do to adjust the Navigation Item and Dropdown placement?

I've been working with Bootstrap dropdowns, but they're not aligning correctly for some reason. I've tried multiple solutions like updating my Bootstrap versions, but none of them seem to be working. Here is the code: <script src=" ...

React does not play well with Bootstrap's JavaScript and may cause it to not function or load properly

Initially, I set up a simple react application by running the command: npx create-react-app appnamehere Following that, I proceeded to install Bootstrap (trying both versions 4 and 5) with the command: npm install bootstrap After this, I included them in ...

Having trouble with clearInterval in my Angular code

After all files have finished running, the array this.currentlyRunning is emptied and its length becomes zero. if(numberOfFiles === 0) { clearInterval(this.repeat); } I conducted a test using console.log and found that even though ...

Error: Attempting to access 'jquery' property on undefined object is not allowed

When using [email protected] in my React JS application, I encountered this error message. Even after installing jQuery and importing the Bootstrap bundle as shown below: import "bootstrap/dist/js/bootstrap.bundle"; I still received the fo ...

jquery tutorial: looping through a function

Hey there, I'm trying to create an image slideshow that fades in and then fades out again, but I'm struggling to figure out how to loop it. Can anyone help? <div class="slideshow"> <img src="img1.jpg"> <img src="img2.jpg"> < ...

What is the best way to notify a JavaScript client from Laravel when a save operation is performed on the database?

Is there a way to automatically refresh the JavaScript DOM when the database is updated, without having to reload the page? Initially, I considered sending an Ajax post request with a 3-second delay, but I've realized that it's not a good idea. ...

When the screen is resized, the embedded iframe moves smoothly to the left side

I recently created a projects page, but I am facing an issue with the iframe embed. Whenever the screen is resized, it keeps shifting to the left. However, what I really want is for it to be centered instead of being on the left side: https://i.stack.imgu ...

Enable the entire button to be clickable without the need for JavaScript by utilizing a Bootstrap 5 button

Is there a way to make a button redirect when clicking anywhere on it, not just the text inside? Here is the button code utilizing Bootstrap 5: <button class="btn btn-rounded btn-primary" type="button">Placeholder Text</button& ...

Is it possible to modify the background color of a checkbox?

I am looking to modify the background color of the checkbox itself, specifically the white square. I have spent a lot of time researching this topic but most articles suggest creating a div and changing its background color, which does not affect the whi ...