Creating an endless variety of modals using HTML - The ultimate guide

Currently, I am in the process of developing a Project Manager website by utilizing w3school's To-do-list tutorial. To enhance the functionality, I have included a detail button (denoted by ...) that triggers a modal displaying task information. However, I am faced with the challenge of manually creating individual modals for each task on the list.
My inquiry is: Is there a method to automatically generate unique modals for every element present in the list?

// Get the modal
var modal = document.getElementsByClassName("modal");
// Click on a close button to hide the current list item
var close = document.getElementsByClassName("close");
// Click on a detail button to show detail of the task item
var detail = document.getElementsByClassName("detail");
var count = 0; // keep track of task count (must be less than 10)
var maxcount = 10;

// Add a "checked" symbol when clicking on a list item
var list = document.querySelector('ul');
list.addEventListener('click', function(ev) {
  if (ev.target.tagName === 'LI') {
    ev.target.classList.toggle('checked');
  }
}, false);

// Create a new list item when clicking on the "Add" button
function newElement() {
  var li = document.createElement("li");
  var inputValue = document.getElementById("myInput").value;
  var t = document.createTextNode(inputValue);
  li.appendChild(t);
  if (inputValue === '') {
    alert("You must write something!");
  } else {
    if (count < maxcount) {
      count = count + 1;
      document.getElementById("myUL").appendChild(li);
    }
  }
  document.getElementById("myInput").value = "";
  // Create close button for each element
  var span = document.createElement("SPAN");
  var txt = document.createTextNode("\u00D7");
  span.className = "close";
  span.appendChild(txt);
  li.appendChild(span);
  // Create detail button for each element
  var span = document.createElement("SPAN");
  var txt = document.createTextNode("\u2026");
  span.className = "detail";
  span.appendChild(txt);
  li.appendChild(span);
  // Function of close button
  for (i = 0; i < close.length; i++) {
    close[i].onclick = function() {
      count = count - 1;
      var div = this.parentElement;
      div.style.display = "none";
    }
  }

  var detail = document.getElementsByClassName("detail");
  var modal = document.getElementsByClassName("modal");
  var span = document.getElementsByClassName("modalclose");
  // Functionality of detail button 

  detail[0].onclick = function() {
    modal[0].style.display = "block";
  }
  span[0].onclick = function() {
    modal[0].style.display = "none";
  }
  window.onclick = function(event0) {
    if (event0.target == modal[0]) {
      modal[0].style.display = "none";
    }
  }

  /* Repeat the above sections for multiple tasks */
}
/* CSS styles go here */
<!-- HTML structure goes here -->

Answer №1

This solution appears to be effective

  1. Avoid directly manipulating styles with CSS; opt for changing the className of elements using .classList.add/.remove/.toggle
  2. Prefer using .addEventListener('click', /* function reference here */) over .onclick handler
  3. To minimize the number of click handlers, attach a click handler to the document and utilize event bubbling to check the event target
  4. Take note that document.getElementsByClassName returns a live HTMLCollection, reflecting any changes made dynamically
  5. When adding .details and .modals simultaneously, consider their positions in their respective HTMLCollections
  6. To handle repetitive modals effectively, retain one static HTML modal as a template and clone it when needed

// Revised JavaScript code will go here
// Revised CSS code will go here
<div>
  <p contenteditable="true">Edit task's name</p>
  <input type="text" id="myInput" placeholder="Title...">
  <span onclick="newElement()" class="addBtn"> Add </span>
</div>

<ul id="myUL"></ul>

<!-- Modal structure -->
<div class="modal-template">
  <div class="modal-content">
    <div class="modal-header">
      <span class="modalclose">&times;</span>
      <h2>Modal Header</h2>
    </div>
    <div class="modal-body">
      <p>Due date <span class="due-date-count"></span>:</p>
      <input type="date" name="duedate">
      // Additional modal content goes here
    </div>
    <div class="modal-footer">
      <h3>Modal Footer</h3>
    </div>
  </div>
</div>

Answer №2

To get started, follow these steps:

  1. Firstly, create a <div id="dynamicDiv"> on your webpage where you intend to display the modals
  2. Next, use JavaScript to manually write the modal descriptions as strings and store them in variables like
    var modalDesc = '... my modal description as html ...'
    for each modal
  3. Now, insert the string within the div using this code -
    document.getElementById('dynamicDiv').innerHTML = modalDesc1 + '<br>' + modalDesc2 ...

UPDATE:

If you have multiple cases, you can utilize loops if your modal structures are similar but with different information or structural values.

Otherwise, you will need to declare each modal differently.

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

Diverse Range of Exports Available in React Component Library

I have been working on developing a component library consisting of multiple independent components. My objective is to enable users to easily import and use these components in their projects, similar to the following: import One from 'component-lib ...

Is it possible to use a TypeScript Angular (click) event with an object property as the value?

Seeking assistance in creating a dynamic error card featuring various error messages along with a retry button. Below is a snippet from my TypeScript object: errorCard: any = []; if(error) { this.errorCard.errorMessage = "Oops, please try again"; ...

Tips for confirming date is earlier than current date in Reactjs?

Looking for guidance on how to ensure a date selected by a user is always before the current date when using Material UI in my project. For instance, if it's January 6th, 2021 and the user selects either January 5th or 6th that would be acceptable. Ho ...

Different scenarios call for different techniques when it comes to matching text between special characters

I encounter different scenarios where strings are involved. The goal is to extract the text in between the || symbols. If there is only one ||, then the first part should be taken. For example: Useless information|| basic information|| advanced informa ...

Incorrect CSS percentage calculations detected on mobile devices

My webpage consists of three large containers, each with an alpha transparent background. While they display correctly on desktop browsers, I'm facing alignment issues on tablets (both iOS and Android) and iPhones where the percentage sum seems to be ...

Ways to grab attention as a visitor leaves a website

My company specializes in creating web surveys. Occasionally, we are asked if it is possible to conduct an exit survey on a website. This would involve displaying a "popup" to visitors as they are about to leave the site, prompting them to take a quick sur ...

What is the best method for converting a plist file into a json file?

Is there a way to convert an existing plist file into a JSON file using one of the following programming languages: JavaScript, Java, Objective-C, Python, or Ruby? Any suggestions on how to do this? ...

Interact with database using Ajax and Codeigniter (utilizing Bootstrap modal)

My goal is to create an advanced search feature with an interactive button that opens input fields and dropdown menus. To populate these dropdown menus with data from the database without overloading the page, I plan to use AJAX when the user triggers the ...

Stopping the use of <script> tags within HTML form submissions

After launching my website at , I discovered that a user is attempting to redirect it to different websites using HTML form input tags. While I'm unsure of the exact method they are employing, I am seeking a way to block users from entering these nefa ...

Discrepancy in Syntax Highlighting in HAML Code

Hopefully this is an easy fix, as I am struggling with highlighting some HAML code using the prism library. %pre %code.language-haml &#37;header.post-header &#37;h1= data.title &#37;time{ datetime: data.date }= pretty_date(data.d ...

JS | Attach a variable to the entire class scope

Is it possible to bind a variable (this) to an entire class without needing to pass arguments from one function to another? I have created a code sample on CodePen: https://codepen.io/anon/pen/vRBVRj class Person { constructor(name) { this. ...

Extract form input to utilize in nodemailer

Currently I am working on a form implementation where I intend to utilize nodemailer for sending test emails to myself. My goal is to have the email inputted into the form dynamically appear in both the "to" and "subject" fields when the user submits the f ...

Run a PHP statement when a JavaScript condition evaluates to true

I am attempting to run a php statement if my javascript condition is true. Here is the code snippet that I have written: <input id="checkbox1" type="checkbox"> MSI<br></input> <script> $(document).ready(function(){ $(&apos ...

Error: Attempted the use of 'append' method on an object lacking the implementation of FormData interface, with both processData and contentType set to false

Apologies for any English errors. I am attempting to use ajax to submit a form, and here is my JavaScript code: $("#formPublicidad").on('submit', function(event) { event.preventDefault(); var dataForm = new FormData(document.getElementBy ...

There seems to be an issue with saving posts to the database when using RESTful services

Problem with POST request not saving data properly in database I am using Node.js with Express and Mongoose for RESTful services. Here is my model: var mongoose = require('mongoose'), Schema = mongoose.Schema; var bookModel = new Schema({ title ...

The jQuery code is experiencing issues when trying to target an array as an id element, such as attempting to set the value of $("#pageid[0]") to "1234"

I have multiple text boxes with IDs stored in an array as pageid[] For example, the ID of the first text box is pageid[0] I am attempting to perform an action on that text box based on its ID For instance: $("#pageid[0]").val("1234"); I am not seeing ...

Arranging divs with Bootstrap version 4

Is it necessary to specify the order for each screen size breakpoint when displaying 2 divs in different orders based on the screen size? <div class="order-xs-2 order-sm-2 order-md-2 order-lg-1 order-xl-1"> <div class="order-xs-1 order-sm-1 order ...

Associate an alternate attribute that is not displayed in the HTML component

Imagine there is a collection of objects like - var options = [{ id: "1", name: "option1" }, { id: "2", name: "option2" } ]; The following code snippet is used to search through the list of options and assign the selected option to anot ...

Switch up the current Slick Carousel display by utilizing a div element

We have implemented the slick carousel to show only one slide at a time within the <div class='item__wrapper'>. Beneath this are three items, and we want the slick carousel to update when any of these items are clicked. Issues Using item ...

What is the best way to ensure that all the responses to questions in HTML yield a singular outcome?

Can you help me figure out how to link all the answers to questions or user preferences to one ultimate result? I love how Craigslist guides users through their preferences to lead them to one specific outcome. For example, how can I connect these two ques ...