Generate a Customized Modal for a Memo Capturer Program

I am currently developing a basic note-taking application using vanilla JavaScript. I want the program to add notes with a modal that displays the text when clicked. However, my current implementation adds the note below the input box and includes the modal button. When clicking the modal button for the first time, nothing happens. On the second click, both the text and modal button disappear.

    <!DOCTYPE html>
<head>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="caa8a5a5beb9beb8abba8afee4ffe4f9">[email protected]</a>/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Note Tracker</title>
    
<style>
body {font-family: Arial, Helvetica, sans-serif;}

/* The Modal (background) */
.modal {
  display: none; /* Hidden by default */
  position: fixed; /* Stay in place */
  z-index: 1; /* Sit on top */
  padding-top: 100px; /* Location of the box */
  left: 0;
  top: 0;
  width: 100%; /* Full width */
  height: 100%; /* Full height */
  overflow: auto; /* Enable scroll if needed */
  background-color: rgb(0,0,0); /* Fallback color */
  background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}

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

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

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

.success {
  background-color: #ddffdd;
  border-left: 6px solid #4CAF50;
}
</style>
</head>
<body>
    <h1>Note Tracker Web App</h1>
    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fc9e9393888f888e9d8cbcc8d2c9d2cf">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script>
    <label for="iNote">Input Note:</label><br>
    <br>
    <textarea id="inote" name="inote" rows="4" cols="50">
    </textarea>
    <br>
    <button type="button" id="btn" onclick="addNote()">Add Note</button>
    <br><br>
    <div id="noteList">
      <span class="close">&times;</span>

    </div>

    <script src="scripts.js"></script>

</body>

The JavaScript function below creates the note and then appends it along with the modal button:

    function addNote(){
    
    var item = document.getElementById("inote").value
    var text = document.createTextNode(item)
    var newItem = document.createElement("P")
    newItem.appendChild(text)
    document.getElementById("noteList").appendChild(newItem)
    
    var x = document.createElement("BUTTON");
    x.id = "someId";
    //x.onclick ="modalOpen()";
    x.onclick = function(){
        var modal = document.getElementById("noteList");
        var btn = document.getElementById("someId");
        btn.onclick = function() {
            modal.style.display = "none";
        }
    };
    var t = document.createTextNode("Open Modal");
    x.appendChild(t);
    document.getElementById("noteList").appendChild(x); 
    var z = document.createElement("BR");
    document.getElementById("noteList").appendChild(z);

    var newElem = document.createElement("BR");
    document.getElementById("noteList").appendChild(newElem);

}

Answer №1

Initially, you only attach an event listener for the click event by placing x.onclick outside of the function.

Answer №2

Perhaps this explanation will be beneficial.

We utilize the "note-list" to manage our list effectively. I have introduced a modal element that can be activated by clicking on the "new note" button.

Within this context, I manipulate opacity and z-index properties to display this modal window. There may be room for improvement in this regard.

const newNote = document.getElementById('new-note'),
  addNote = document.getElementById('add-note');
let myModal = document.getElementById('my-modal');
newNote.addEventListener('click', () => {
  myModal.style.zIndex = 99;
  myModal.style.opacity = 1;
});

addNote.addEventListener('click', () => {
  let note = document.getElementById('note'),
    noteList = document.getElementById('note-list');

  if (note.value !== '') {
    let _el = document.createElement('li');
    _el.innerHTML = note.value;
    
    let _a = document.createElement('a');
    _a.innerHTML = 'delete';
    
    _el.appendChild(_a);
    noteList.appendChild(_el);
    note.value = '';
    myModal.style.zIndex = -1;
    myModal.style.opacity = 0;
    
    _a.addEventListener('click', (e) => {
        e.target.parentNode.remove();
    });
  } else {
    alert('note can not empty');
  }
});
#my-modal {
  width: 100%;
  height: 100%;
  z-index: -1;
  opacity: 0;
  position: absolute;
  background: rgba(0, 0, 0, 0.5);
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.modal-wrapper {
  border-radius: .5rem;
  background: #fff;
  display: block;
  padding: 1rem;
  margin-top: 20%;
}

ul {
display: block;
}

#note-list li {
display: block;
margin-bottom: .5rem;
border: 1px solid #efefef;
background: #f7f7f7;
border-radius: .5rem;
position: relative;
padding: 1rem;
width: 70%;
}

#note-list li a{
position: absolute;
right: 0;
top: 0;
background: tomato;
padding: 1rem;
color: #fff;
}


.modal-wrapper * {
  display: block;
  margin: .5rem auto;
  width: 90%;
  text-align: center;
}
<h1>Note Taker App</h1>

<div class="note-wrapper">
  <ul id="note-list">
  </ul>
  <button id="new-note">New Note</button>
</div>

<div id="my-modal">
  <div class="modal-wrapper">
    <label for="note">Your Note</label>
    <input type="text" name="note" id="note">
    <button id="add-note">add note</button>
  </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

Switching classes in jQuery for Internet Explorer 8

I am attempting to update the color of a header when it reaches a certain scroll position. I have implemented this script using jQuery: var $document = jQuery(document), $element = jQuery('#header'), className = 'red'; $docume ...

The type 'number' cannot be assigned to the type 'Element'

Currently, I am developing a custom hook called useArray in React with TypeScript. This hook handles array methods such as push, update, remove, etc. It works perfectly fine in JavaScript, but encounters errors in TypeScript. Below is the snippet of code f ...

TypeScript multi-dimensional array type declaration

I currently have an array that looks like this: handlers: string[][] For example, it contains: [["click", "inc"], ["mousedown", "dec"]] Now, I want to restructure it to look like this: [[{ handler: "click" ...

Leveraging UseRouter.query Data in Next.js Content Display

I'm currently diving into routing in Next.js and running into an issue where the query values are not being included in the HTML response. Despite recognizing that isReady is false and the return is happening before the variables are set, I'm uns ...

Prevent automatic scrolling to the top following an AJAX request

Question about Preventing Scrolling to Top: How can I prevent a web page from scrolling to the top when a link triggers javascript? Whenever an ajax request occurs, my browser automatically scrolls to the top. In order to return to my desired div sect ...

You may encounter an error in cpanel due to the include path being set to '.:/opt/cpanel/ea-php70/root/usr/share/pear'

While testing my PHP application on WampServer (localhost), everything worked perfectly. However, when I uploaded the same application to my web server, I encountered the following issue: PHP Fatal error: require_once(): Failed opening required 'util ...

Identifying and capturing changes in child scope events or properties in Angular

I am encountering an issue with my form directive where I need to intercept ng-click events nested within varying child scopes of the form element. However, I am struggling to hook into these events or child scope properties in a generic way. For demonstr ...

Limiting Ant Design Date range Picker to display just a single month

insert image description here According to the documentation, the date range picker is supposed to display two months on the calendar, but it's only showing one month. I carefully reviewed the documentation and made a change from storing a single va ...

Is your Node.js asynchronous parallel function not performing as expected?

I have a series of promises that I need to execute sequentially, but it's getting messy with all the promise returns. To simplify this process, I decided to use the async library and tried out the parallel method. However, instead of running one after ...

Executing mailto URLs from action method

As a newcomer to MVC, I am looking to create an action method in MVC that triggers Mailto:?body=body goes here.&subject=test subject, allowing the default mail client to automatically populate the user's email. Currently, I have a List<String&g ...

Finding the position of the biggest floating point number in the array

What is the best way to find the index of the largest element in an array of floating point numbers? [0.000004619778924223204, 0.8323721355744392, 0.9573732678543363, 1.2476616422122455e-14, 2.846605856163335e-8] Once the index of the largest element is ...

When the JSON object is transferred to the node server, it undergoes modifications

With the following code snippet, I have managed to develop a function that generates JSON data and transmits it to server.js (my node server). function deleteEmail(i) { emailObj.splice(i, 1); var general = {}; var table = [] general.table ...

Limiting the number of characters in PHP/MySQL

Here is a glimpse into the scenario I am currently facing: The content, including the heading, text, and image, is all dynamically generated based on user input. Users have the option to include an image and choose the text for both the heading and main c ...

How to properly handle file uploads and get the correct image path from Node Js (Express) to React Js?

Currently, I am working on my local system developing a file upload feature using node js. My project file structure looks like this: Project ..client .... source code of React App ..Server ....uploads ......avatar ........image.png ....index.js In this ...

Ways to effectively pair a radio button with a dropdown menu

function radioCheck() { document.getElementById("last").checked = "checked"; } <label> <input type="radio" name="Ppub" value="" checked="checked">All Dates </label> <br> <label> <input type="radio" id="last" name="Ppu ...

Ways to create CSS styles dynamically in PHP using database-driven methods

Currently, I am in the process of developing an application that gives users the ability to select different style options within the app. These choices will then be utilized to create a dynamic web page. I am curious about the various methods available to ...

Organizing a Collection of Likes within an AngularJS Service

I have a like button on my profile page that, when clicked, should add the user's like to an array and store it in the database. Within my profile controller, I have the following code: $scope.likeProfile = UserService.likeProfile(loggedInUser,$stat ...

Discover the secret to creating a seamless looping effect on text using CSS gradients, giving the illusion of an endless loop

Could use some assistance with looping this gradient smoothly over the text without any annoying jumps appearing during the animation. Is there a way to achieve a seamless movement across the text? Any suggestions on how to approach this? Here is a liv ...

Error encountered while building with Vite: Parsing issue when importing PNG images in a Vue.js project

While working on my app, I encountered a problem. In my code, I have the following line: <img class="h-full w-full object-cover" src="../assets/img/loginSignUpForms/Login.PNG" alt="" ...

Accessing a specific segment of HTML using Java

Attempting to navigate through a bunch of HTML, I'm aiming to isolate specific sections. I'm specifically looking to retrieve 'THISISTHEBITIWANT' from the following HTML code. <li class="aClass"> <a href="example/THISISTHEB ...