Want to learn the process of closing a modal using Javascript?

I am working on implementing 6 different modals, each featuring an exit button named 'modal-box__exit-button'. I have attempted to use JavaScript to close the modals when the exit button is clicked, but it seems like my code may have some errors. Here is what I have tried:

const btns = document.querySelectorAll("[data-target]");
  const closedModal = document.querySelectorAll(".modal-box__exit-button");

  btns.forEach(btn => {
    btn.addEventListener('click', () => {
      document.querySelector(btn.dataset.target).classList.add('modal-pop-up--active');

      if (typeof window != 'undefined' && window.document) {
        document.body.style.overflow = 'hidden';
      }
    })
  })

  closedModal.forEach(btn => {
    btn.addEventListener('click', () => {
      btns.classList.remove('modal-pop-up--active');
    })
  })
<div class="modal-pop-up" id="modal4">
  <div class="modal-block">
    <div class="modal-box__exit-button">
      <svg stroke="currentColor" fill="currentColor" stroke-width="0" version="1.2" baseProfile="tiny"
        viewBox="0 0 24 24" class="btn" height="1em" width="1em" xmlns="http://www.w3.org/2000/svg">
        <path
          d="M17.414 6.586c-.78-.781-2.048-.781-2.828 0l-2.586 2.586-2.586-2.586c-.78-.781-2.048-.781-2.828 0-.781.781-.781 2.047 0 2.828l2.585 2.586-2.585 2.586c-.781.781-.781 2.047 0 2.828.39.391.902.586 1.414.586s1.024-.195 1.414-.586l2.586-2.586 2.586 2.586c.39.391.902.586 1.414.586s1.024-.195 1.414-.586c.781-.781.781-2.047 0-2.828l-2.585-2.586 2.585-2.586c.781-.781.781-2.047 0-2.828z">
        </path>
      </svg>
    </div>
    <div class="modal-content-inner">
      <h5>{{ pages['why-we-dont-offer-free-shipping'].title }}</h5> 
      <p>{{ pages['why-we-dont-offer-free-shipping'].content }} </p>
    </div>
    <div class="modal-box__contact-button">
      <a href="/pages/contact-us" class="bottom-button">Contact Us</a>
    </div>
  </div>
</div>

(All modals follow a similar structure with differing content).

Answer №1

const closeModalsBtn = document.querySelectorAll(".modal-box__exit-button");
closeModalsBtn.forEach(closeBtn=>{
  closeBtn.addEventListener('click' , (e) =>{
    e.currentTarget.parentElement.parentElement.style.display = 'none'
  })
})
.modal-pop-up{
  border : 2px dashed red;
  margin: 20px auto;
}
<div class="modal-pop-up" id="modal4">
  <div class="modal-block">
    <div class="modal-box__exit-button">
      <svg stroke="currentColor" fill="currentColor" stroke-width="0" version="1.2" baseProfile="tiny"
        viewBox="0 0 24 24" class="btn" height="1em" width="1em" xmlns="http://www.w3.org/2000/svg">
        <path
          d="M17.414 6.586c-.78-.781-2.048-.781-2.828 0l-2.586 2.586-2.586-2.586c-.78-.781-2.048-.781-2.828 0-.781.781-.781 2.047 0 2.828l2.585 2.586-2.585 2.586c-.781.781-.781 2.047 0 2.828.39.391.902.586 1.414.586s1.024-.195 1.414-.586l2.586-2.586 2.586 2.586c.39.391.902.586 1.414.586s1.024-.195 1.414-.586c.781-.781.781-2.047 0-2.828l-2.585-2.586 2.585-2.586c.781-.781.781-2.047 0-2.828z"></path>
      </svg>
    </div>
    <div class="modal-content-inner">
      <h5>{{ pages['why-we-dont-offer-free-shipping'].title }}</h5> 
      <p>{{ pages['why-we-dont-offer-free-shipping'].content }} </p>
    </div>
    <div class="modal-box__contact-button">
      <a href="/pages/contact-us" class="bottom-button">Contact Us</a>
    </div>
  </div>
</div>
<div class="modal-pop-up" id="modal5">
  <div class="modal-block">
    <div class="modal-box__exit-button">
      <svg stroke="currentColor" fill="currentColor" stroke-width="0" version="1.2" baseProfile="tiny"
        viewBox="0 0 24 24" class="btn" height="1em" width="1em" xmlns="http://www.w3.org/2000/svg">
        <path
          d="M17.414 6.586c-.78-.781-2.048-.781-2.828 0l-2.586 2.586-2.586-2.586c-.78-.781-2.048-.781-2.828 0-.781.781-.781 2.047 0 2.828l2.585 2.586-2.585 2.586c-.781.781-.781 2.047 0 2.828.39.391.902.586 1.414.586s1.024-.195 1.414-.586l2.586-2.586 2.586 2.586c.39.391.902.586 1.414.586s1.024-.195 1.414-.586c.781-.781.781-2.047 0-2.828l-2.585-2.586 2.585-2.586c.781-.781.781-2.047 0-2.828z"></path>
      </svg>
    </div>
    <div class="modal-content-inner">
      <h5>{{ pages['why-we-dont-offer-free-shipping'].title }}</h5> 
      <p>{{ pages['why-we-dont-offer-free-shipping'].content }} </p>
    </div>
    <div class="modal-box__contact-button">
      <a href="/pages/contact-us" class="bottom-button">Contact Us</a>
    </div>
  </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

troubleshooting responsive design issues with Bootstrap and PHP

this is the issue I'm facing and what I require: Please provide assistance with fixing the code for my website project. What exactly is the problem and how can it be resolved? Thank you. <?php include 'init.php'; $stmt = $con->prepar ...

Removing an item from a Redis list using Node.js

Recently, I encountered a challenge involving managing a list in Redis using Node.js. I successfully stored a list with the following code snippet: client.rpush(['room_'+room, data.customClient], function(err, reply) { client.lrange(&ap ...

Dominating React Components with Unique CSS Styles

Currently, I have developed a NavBar component. I've implemented some JavaScript code that changes the navbar's background color once it reaches 50px. However, I am facing an issue in applying this scroll effect to only one specific file and not ...

Modifying routes within the beforeEach function causes issues when the callback incorrectly passes in erroneous routes to and from

I'm currently in the process of developing a mobile frontend using Vue. My goal is to have route transitions dynamically change to slide either left or right based on the current tab index. To accomplish this, I've set up a transition component ...

Querying multiple collections in MongoDB using aggregate and populate functions to search across multiple fields

Within our database, we have two collections: Ad and Company. It is possible for a company to have multiple ads associated with it. We are in need of an API endpoint that can retrieve ads based on a keyword search. This search should span across the compa ...

HTML - Ways to showcase multiple forms on a single row?

I have three forms in my Flask application that I want to display in a single line rather than one after the other. Is there a way to achieve this without using CSS? Here is the HTML snippet: <form action="/pull_entity_by_manufacturer" metho ...

Generate a list of files and transfer them to an input file

I am currently working on creating a drag and drop area where I can retrieve dataTransfer items using webkitGetAsEntry, and then differentiate between directories and files. My goal is to convert these files into a FileList and transfer them to a file inp ...

Error in routing of submit button in Express.js

While attempting to create a basic "to-do list" using HTML requests, I encountered an issue with the PATCH request. Instead of redirecting to "/", it redirected to "/posts/2" and displayed the message "Cannot POST /posts/2", without updating the array elem ...

Is there a way to make a button on a single div only affect that specific div

I have a PHP query that echoes a div for each row in the table. I want the div to slide up and then, when the user clicks the "read more" button, the div slides down. However, since it is echoed in a loop, all the divs have the same IDs and classes. I wo ...

Expanding the outer div horizontally by using inner divs with scroll

Is there a way to ensure that all child divs are displayed on the same line within the outer div without wrapping to a second line? The width of the outer div should be fixed so that a scrollbar is visible, allowing us to scroll and view all inner divs. h ...

Customizing the Slider Range with HTML DOM Style's BackgroundImage Attribute

I have a slider range that I'd like to modify using JavaScript. Specifically, I want to change its background-image property. To achieve this, I attempted the following script: document.getElementById("range").style.backgroundImage = "linear-gradient ...

Create a variable and set it equal to the value of a form

I'm having trouble setting a value to a hidden form field that needs to come from a query string parameter. The function that extracts the query string parameter is working properly, but the function that assigns this variable to the hidden form field ...

Escape key does not close the modal dialogue box

I’ve customized the codrops slide & push menu (http://tympanus.net/codrops/2013/04/17/slide-and-push-menus/) to create an overlay on a webpage. Although it functions as intended, I’m struggling to implement a way to close it by pressing the escape ...

JavaScript: utilizing a function as a hash key

In my program, I need to execute different functions based on the input. If the input matches one of the predefined keys, I want to invoke the corresponding function along with some parameters: var functions = { 'key1': firstFunction, ' ...

Burger menu floating above container block element

I have set up a bootstrap container with the following styling: .container { margin-top: 12em; font-family: 'Amatic SC', cursive; border-bottom: 1px solid; border-color: #800000; } The purpose behind this is to have my navigatio ...

Ways to hear a variable using Google Translate

We're utilizing HTML5 and Javascript. Imagine we have a list containing the names of all players from Barcelona (for example, name = 'Lionel Messi'). I want to make the player's name audible. To achieve this, I would use: var narrator ...

When Css is incorporated within a text, it prevents the use of " " from functioning properly

I am currently developing a GUI application using Qt 4.8. I have a label that displays text in white (the stylesheet has already been set up for this) and I want to change the color of the word "UPDATE" to red. Here is my initial code: //all text in whit ...

What is the best way to refresh a page during an ajax call while also resetting all form fields?

Each time an ajax request is made, the page should refresh without clearing all form fields upon loading Custom Form <form method='post'> <input type='text' placeholder='product'/> <input type='number&a ...

Ways of incorporating text in a parallelogram shape

Here is the HTML code with ID attributes applied to both divs: <div id="herotext"> <div id="banner"></div> <h1 id="maintitle">Hey, I'm Charlie</h1> <p>This websi ...

Pressing the reset button will restore the table to its original

As a new React developer with experience mainly in hooks, I have been struggling to find a good example involving hooks. Currently, I am working on implementing an antd table with search functionality. My question is, when a user types something into the ...