Using incrementing CSS IDs to implement multiple modal windows on a single webpage

I am faced with a dilemma where I have more than eight modals on a single page, each having a unique CSS id. Initially, I had a JavaScript code snippet that worked perfectly for a sole modal, but it failed to target all the different CSS ids. As someone with limited knowledge in JavaScript, I am seeking a solution on how to dynamically target each modal using a counter variable.

<button class="fsc-modal-button">Read Bio</button>
<div class="fsc-modal" id="fsc-modal-1">
    <div class="fsc-modal-content"><span class="fsc-modal-close">×</span</div>
</div>

<button class="fsc-modal-button">Read Bio</button>
<div class="fsc-modal" id="fsc-modal-2">
    <div class="fsc-modal-content"><span class="fsc-modal-close">×</span</div>
</div>


<script type="text/javascript">

var button = document.getElementsByClassName('fsc-modal-button')[0];
var modal = document.getElementsByClassName('fsc-modal')[0];
var span = document.getElementsByClassName('fsc-modal-close')[0];

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

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

window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}
</script>

Answer №1

function launchModal(identifier) {
  var triggerButton = document.getElementsByClassName('fsc-modal-button')[0];
  var modalWindow = document.getElementById('fsc-modal-' + identifier);
  var closeBtn = document.getElementsByClassName('fsc-modal-close')[0];

  triggerButton.onclick = function() {
     modalWindow.style.display = "block";
  }

  closeBtn.onclick = function() {
   modalWindow.style.display = "none";
  }

  window.onclick = function(evt) {
    if (evt.target == modalWindow) {
     modalWindow.style.display = "none";
    }
  }
}

To utilize this script, simply invoke launchModal(1) or any other number.

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

Determining the Clicked Button in ReactJS

I need help with a simple coding requirement that involves detecting which button is clicked. Below is the code snippet: import React, { useState } from 'react' const App = () => { const data = [ ['Hotel 1A', ['A']], ...

Detection of the page rendering time for an angular spa application's final section

Our team is working with an angular SPA and we are seeking a solution to generate an event once a page has finished rendering and all ajax calls have been completed. We are open to any suggestions on how we can achieve this without having to implement it ...

Having trouble accessing the latest props within a setInterval in a React functional component

I'm facing an issue where I can't seem to access the updated prop within setInterval inside Component1; instead, it keeps showing me the old value. Here's the code snippet I'm working with: import { useState, useEffect } from "reac ...

Can Threejs enable us to assign unique colors to each face of a cube?

// In this code snippet, we are loading a mesh and adding it to the scene. var loader = new THREE.JSONLoader(); loader.load( "models/cubic.js", function(geometry){ var material = new THREE.MeshLambertMaterial({color: 0x55B66 ...

How can one easily retrieve the callback function arguments from outside the function?

Here is a snippet of my code: var jenkins = require('jenkins')('http://192.168.1.5:8080'); var job_name = undefined; jenkins.job.list(function doneGetting(err, list) { if (err) throw err; job_name = list[0].name; }); jenkins. ...

How can I modify this section of the code in Google Script to retrieve all columns?

My question is, how can I modify this code to fetch all columns from the array instead of just [0,1,2,3] Here is the line of code in question: const new_table = [0,1,2,3].map(x => make_row_from_col(this_table, x)).join('\n'); Using obje ...

What are the steps to troubleshooting using VS Code and Chrome browser with Webpack?

Can anyone provide guidance on how to debug webpack in VS Code with the Chrome browser? As a beginner in programming, I'm struggling because webpack minifies everything into one line which makes traditional debugging methods ineffective. I haven' ...

Error: Placeholder Loading Card malfunctioning

I attempted to incorporate a Placeholder Loading Card into my bootstrap 4 website by adding a sample image, but encountered an issue. The placeholder does not work when the website is loading. Is it supposed to always animate? Does anyone have knowledge ...

Using Javascript, retrieve a custom attribute specific to a checkbox option

How can I access the custom attribute "mem_name" value? <input class="messageCheckbox" type="checkbox" value="3" mem_name='ABC' name="checkmember" > <input class="messageCheckbox" type="checkbox" value="1" mem_name='PQR' name ...

Tips for arranging a group of objects based on a nested key within each object

i have a collection of objects that I need to sort based on their id. here is the information: { 1918: { id: "1544596802835", item_id: "1918", label: "Soft Touch Salt Free Mint 500 ml (000001400045)", combo_items: false } 6325: { ...

Editing HTML using the retrieved jQuery html() content

I need to modify some HTML that is stored in a variable. For example: var testhtml = $('.agenda-rename').html(); console.log($('input',testhtml).attr('name')); I also tried the following: console.log($(testhtml).find(' ...

Matching objects in an array based on a specific property using the key of another object

To display information in the UI based on matching values between the data.examples array object's name.value property and the keys in the wcObject.notCoveredList, we need to create a logic. If there is a match, all corresponding values from wcObject ...

Displaying files from Google Drive on a web page

How can I display documents saved on my drive on a webpage with the ability for users to download them directly? Any advice on how to achieve this would be greatly appreciated. Thank you! ...

Steps for converting a JSON-encoded object into a JavaScript variable

Is there a better way to return a JSON object to an Ajax call without using `json_encode`? My question is related to making the key a variable in JavaScript, which throws a "not defined error". Specifically, this line of code causes the issue: var display ...

Creating a Responsive Bootstrap Webpage

I attempted to replicate a sign-in page using Bootstrap from this link: Prior to this, I had already created a page without using Bootstrap code. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Mainpage.aspx.cs" Inherits="project.Mainpage" ...

Textarea generated on-the-fly without any assigned value

My goal is to enable users to edit the text within a paragraph on a website. I am attempting to replace the <p> tags with <textarea> tags using the .replaceWith() function. However, when I try to retrieve the value of the textarea, it comes bac ...

Transferring HTML variables to CSS

I've been searching for an answer without much luck. Is it possible to transfer variables from HTML to CSS, maybe using data attributes? I want to display different backgrounds based on vendors using media queries on brand pages. I know inline CSS d ...

Parsing the CSV file contents according to the specified columns

Currently, I'm involved in a project using AngularJS where I need to extract data from a CSV file column by column using JavaScript. So far, I've successfully retrieved the CSV data and displayed it in the console. While I've managed to sepa ...

Why does my text keep drifting towards the left edge?

After spending a day learning CSS and HTML, I decided to recreate a website from a YouTube video and add my own customizations. I was able to center the text in my introduction successfully. However, upon reviewing my progress (see screenshot here), it is ...

Keeping an Rxjs observable alive despite encountering errors by simply ignoring them

I am passing some values to an rxjs pipe and then subscribing to them. If there are any errors, I want to skip them and proceed with the remaining inputs. of('foo', 'bar', 'error', 'bazz', 'nar', 'erro ...