The modal is not displayed when the on click listener is triggered

I'm a beginner in the world of programming and I'm currently working on creating modals that pop up when clicked. However, I'm facing an issue where the pop-up message doesn't appear when I click the button. Oddly enough, only the overlay seems to work! I've already ruled out using a tag instead of buttons as the culprit by testing both options without success.

Check out my code snippet below:

const openModalButtons = document.querySelectorAll('[data-modal-target]')
const closeModalButtons = document.querySelectorAll('[data-close-button]')
const overlay = document.getElementById('overlay')

openModalButtons.forEach(button => {
  button.addEventListener('click', () => {
    const modal = document.querySelector(button.dataset.modalTarget)
    openModal(modal)
    console.log("opened successfully");
  })
})

overlay.addEventListener('click', () => {
  const modals = document.querySelectorAll('.modal.active')
  modals.forEach(modal => {
    closeModal(modal)
  })
})

closeModalButtons.forEach(button => {
  button.addEventListener('click', () => {
    const modal = button.closest('.modal')
    closeModal(modal)
  })
})

function openModal(modal) {
  if (modal == null) return
  modal.classList.add('active')
  overlay.classList.add('active')
}

function closeModal(modal) {
  if (modal == null) return
  modal.classList.remove('active')
  overlay.classList.remove('active')
}
body {
    background-image: linear-gradient(rgba(255,255,255,.2), rgba(255,255,255,.2)), url('images/blue_checkered_table.jpg'); 
}
  
.title {
    display:inline-block;
    text-decoration: none;
    padding: 15px;
    -webkit-text-stroke: 1px black;
    color: white;
    text-shadow:
        2px 2px 0 #000,
      -1px -1px 0 #000,  
       1px -1px 0 #000,
       -1px 1px 0 #000,
        1px 1px 0 #000;
}

.title:hover {
    text-decoration: none;
    -webkit-text-stroke: 1px black;
    color: #76B9F6;
    text-shadow:
        2px 2px 0 black,
      -1px -1px 0 black,  
       1px -1px 0 black,
       -1px 1px 0 black,
        1px 1px 0 black;
} 

#mySidenav a {
    margin: 120px 0px 0px 0px;
    position: absolute;
    left: -150px;
    transition: 0.3s;
    padding: 20px;
    width: 200px;
    text-decoration: none;
    font-size: 20px;
    color: white;
    border-radius: 0 5px 5px 0;
  }
  
  #mySidenav a:hover {
    left: 0;
  }
  
  #about {
    display:inline-block;
    text-decoration: none;
    padding: 15px;
    color: white;
    text-shadow:
        2px 2px 0 #000,
      -1px -1px 0 #000,  
       1px -1px 0 #000,
       -1px 1px 0 #000,
        1px 1px 0 #000;
    top: 5px;
    background-color: #4CAF50;
  }
  
  #calendar {
    display:inline-block;
    text-decoration: none;
    padding: 15px;
    color: white;
    text-shadow:
        2px 2px 0 #000,
      -1px -1px 0 #000,  
       1px -1px 0 #000,
       -1px 1px 0 #000,
        1px 1px 0 #000;
    top: 85px;
    background-color: #2196F3;
  }
  
  #todo {
    display:inline-block;
    text-decoration: none;
    padding: 15px;
    color: white;
    text-shadow:
        2px 2px 0 #000,
      -1px -1px 0 #000,  
       1px -1px 0 #000,
       -1px 1px 0 #000,
        1px 1px 0 #000;
    top: 165px;
    background-color: #f44336;
  }
  
  #feedback {
    display:inline-block;
    text-decoration: none;
    padding: 15px;
    color: white;
    text-shadow:
        2px 2px 0 #000,
      -1px -1px 0 #000,  
       1px -1px 0 #000,
       -1px 1px 0 #000,
        1px 1px 0 #000;
    top: 245px;
    background-color: #555
  }

  *, *::after, *::before {
    box-sizing: border-box;
  }
  
  .modal {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%) scale(0);
    transition: 200ms ease-in-out;
    border: 1px solid black;
    border-radius: 10px;
    z-index: 10;
    background-color: white;
    width: 500px;
    max-width: 80%;
  }
  
  .modal.active {
    transform: translate(-50%, -50%) scale(1);
  }
  
  .modal-header {
    padding: 10px 15px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid black;
  }
  
  .modal-header .title {
    font-size: 1.25rem;
    font-weight: bold;
  }
  
  .modal-header .close-button {
    cursor: pointer;
    border: none;
    outline: none;
    background: none;
    font-size: 1.25rem;
    font-weight: bold;
  }
  
  .modal-body {
    padding: 10px 15px;
  }
  
  #overlay {
    position: fixed;
    opacity: 0;
    transition: 200ms ease-in-out;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, .5);
    pointer-events: none;
  }
  
  #overlay.active {
    opacity: 1;
    pointer-events: all;
  }
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Spin the Wheel</title>
   
    <meta name="author" content="Team26">

    <!----------------------------------------------->
    <!--  Meta tag for rendering on mobile devices -->
    <!----------------------------------------------->
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    
    <!----------------------------------------------->
    <!-- CSS: Bootstrap, Firebase, other API -->
    <!----------------------------------------------->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
    <link type="text/css" rel="stylesheet" href="https://cdn.firebase.com/libs/firebaseui/3.5.2/firebaseui.css" />
   
    <!------------------------>
    <!-- Your own CSS files -->
    <!------------------------>
    <link rel="stylesheet" type="text/css" href="mainpage.css">
    <script type="text/javascript" defer src="mainpage.js"></script>
 
</head>
<body>
    <!----------------------->
    <!--  HTML Section -->
    <!----------------------->
<a href="mainpage.html" class="title"><h1>Project Spin The Wheel</h1></a>
<div id="mySidenav" class="sidenav">
    <a data-modal-target="#modal" id="about">About</a>
    <a href="#" id="calendar">Calendar</a>
    <a href="#" id="todo">My To-Do List</a>
    <a href="#" id="feedback">Feedback</a>
  </div>
    <div class="modal" id="modal">
      <div class="modal-header">
        <div class="title">A b o u t  U s . . .</div>
        <button data-close-button class="close-button">&times;</button>
      </div>
      <div class="modal-body">
        Lorem ipsum dolor sit amet consectetur adipisicing elit. 
        Esse quod alias ut illo doloremque eum ipsum obcaecati distinctio debitis reiciendis 
        quae quia soluta totam doloribus quos nesciunt necessitatibus, 
        consectetur quisquam accusamus ex, dolorum, dicta vel? 
        Nostrum voluptatem totam, molestiae rem at ad autem dolor ex aperiam. 
        Amet assumenda eos architecto, dolor placeat deserunt voluptatibus 
        tenetur sint officiis perferendis atque! Voluptatem maxime eius eum 
        dolorem dolor exercitationem quis iusto totam! Repudiandae nobis 
        nesciunt sequi iure! Eligendi, eius libero. Ex, repellat sapiente!
      </div>
    </div>
    <div id="overlay"></div>

  </div>


</body>
    <!----------------------------------------------->
    <!-- JS: Boostrap, Firebase, API related    -->
    <!----------------------------------------------->
    <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e5958a95958097cb8f96a5d4cbd4d3cbd5">[email protected]</a>/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>

    <script src="https://www.gstatic.com/firebasejs/7.9.2/firebase-app.js"></script>
    <script src="https://www.gstatic.com/firebasejs/7.9.2/firebase-auth.js"></script>
    <script src="https://www.gstatic.com/firebasejs/7.9.2/firebase-firestore.js"></script>
    <script src="https://cdn.firebase.com/libs/firebaseui/3.5.2/firebaseui.js"></script>
  
    <!--------------------------------------------------------------------->
    <!-- JS files: Your own JavaScript functions included here    -->
    <!--------------------------------------------------------------------->

     <!--------------------------------------------------------------------->
    <!-- Make calls to your own JavaScript functions, here below-->
    <!---------------------------------------------------------------------->

</html>

Answer №1

Don't forget to specify the CSS properties for displaying the modal correctly. Add display:block to the .active class:

.modal.active {
  transform: translate(-50%, -50%) scale(1);
  display:block;
  top:50%;
  left:50%;
}

Below is a functional code snippet that you can use:

const openModalButtons = document.querySelectorAll('[data-modal-target]')
const closeModalButtons = document.querySelectorAll('[data-close-button]')
const overlay = document.getElementById('overlay')

openModalButtons.forEach(button => {
  button.addEventListener('click', () => {
    const modal = document.querySelector(button.dataset.modalTarget)
    openModal(modal)
    console.log("Modal opened successfully");
  })
})

overlay.addEventListener('click', () => {
  const modals = document.querySelectorAll('.modal.active')
  modals.forEach(modal => {
    closeModal(modal)
  })
})

closeModalButtons.forEach(button => {
  button.addEventListener('click', () => {
    const modal = button.closest('.modal')
    closeModal(modal)
  })
})

function openModal(modal) {

  if (modal == null) return
  modal.classList.add('active')
  overlay.classList.add('active')
}

function closeModal(modal) {
  if (modal == null) return
  modal.classList.remove('active')
  overlay.classList.remove('active')
}
* {
  box-sizing: border-box;
}

.banner {
  background-color: #f5f5f5;
  color: #333;
  padding: 10px;
}

.title {
  font-size: 2rem;
  font-weight: bold;
  text-transform: uppercase;
}

.subtitle {
  font-size: 1.5rem;
  font-style: italic;
}

.container {
  width: 80%;
  margin: 0 auto;
}

.btn {
  background-color: #007bff;
  color: #fff;
  padding: 10px 20px;
  border-radius: 5px;
  text-decoration: none;
  display: inline-block;
}

.btn:hover {
  background-color: #0056b3;
}
<!DOCTYPE html>
<html>
<head>
  <title>Modal Example</title>
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <div class="banner">
    <div class="container">
      <h1 class="title">Welcome to My Website</h1>
      <p class="subtitle">Explore and enjoy!</p>
      <a href="#modal" class="btn">Open Modal</a>
    </div>
  </div>
  
  <div id="overlay"></div>

  <div class="modal" id="modal">
    <div class="content">
      <h2>This is a Modal</h2>
      <p>You can put any content here.</p>
      <button data-close-button class="btn close-btn">Close Modal</button>
    </div>
  </div>

  <script src="script.js"></script>
</body>
</html>

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

The transformation of all relative URLs into absolute URLs is carried out

The issue at hand seems to be peculiar to Chrome and Firefox, as IE does not exhibit the same behavior. In my angular application, I've noticed a strange phenomenon. Once a specific view is loaded, all XHR requests made using relative paths are autom ...

Discovering the Javascript Code Executing on a <span> element with the Help of Chrome Inspector or Firebug

I have encountered a situation where a website is dynamically generating information into <span></span> tags using jQuery. The span has a class of "Price" and an id corresponding to a Product Code, with the data being pulled from a JSON data sh ...

Interoperability between AngularDart and AngularJS

Discovering the Dart language and AngularDart after working with AngularJS has been exciting. However, my biggest concern is whether AngularDart supports all the amazing modules that AngularJS offers. I haven't been able to find any information on whe ...

Troubleshooting: Why is Jquery unable to retrieve image height?

Having trouble using jQuery to find the actual height of the first image nested within a container. I can access the src attribute but not the height. Any suggestions on how to get the accurate height? Is it necessary to retrieve heights via CSS? Unfortu ...

How to hide an image in the React carousel display

I am having an issue with my Carousel, specifically with the image not being displayed even though I have set up the data in a const called items. Here is how my const looks: var items = [ { url:'../../assets/img/hors1.jpg', ...

Hover effect that smoothly transitions to a background image appearing

I want to achieve a smooth fadeIn effect for the background image of a div. Currently, I have a function that displays the background image when hovering over the relevant div, but the transition is too abrupt. I would like it to fade in and out instead of ...

Center the text within a span element in an inline-block container

I'm currently working on a website design that features a flat aesthetic. I have a header at the top and two blocks of different colors placed side by side underneath it. Initially, I attempted to use float left and right for positioning but was recom ...

The foundation of JSON and its structural encoding

Looking to deserialize JSON from Java, here's how it's done: Java jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(graphDTO); JSON "accounts" : [ { "name" : "1009427721", "value" : 16850.79, "children" : ...

The code coverage for the "rendering expectations" test in a particular component is insufficient

In order to test a specific component in my application, I am utilizing react-test-render. The test is intended to ensure that the component renders properly. Despite defining all the necessary properties for the component in the test file, the test cover ...

What is the best way to set up a server-sent-events broadcast feature in totaljs?

Let's imagine this situation: Client1 and Client2 are currently in session1 Meanwhile, Client3 and Client4 are part of session2 My aim now is to send event "a" to all clients in session1 exclusively. I came across this example: https://github ...

Display substitute text for the date input field

When using input types date and datetime-local, the placeholder attribute does not work directly. <input type="date" placeholder="Date" /> <input type="datetime-local" placeholder="Date" /> Instead, the ...

Pass a parameter to an AJAX request in order to retrieve data from a JSON file that is limited to a specific

I am working with a JSON file named example.json, structured as follows: { "User1": [{ "Age":21, "Dogs":5, "Cats":0 }], "User2": [{ "Age":19, "Dogs":2, "Cats":1 }] "User3 ...

Tips for incorporating API-provided CSS values into AngularJS expressions for stylish card customization

I am in the process of creating unique Pokemon cards that pull data from an API. My question is, how can I apply specific CSS styling to each card directly from the API, similar to how I have utilized AngularJS to render the information? So far, I have su ...

An advanced view engine capable of handling both ajax requests and direct function calls

In Node.js (Express), I am seeking a method to present a template in two different ways: one normally as HTML and the other as JSON, specifically for Ajax requests. Assume I have a swig template structured like this: {% extends 'layout.html' %} ...

Tips for implementing a regular expression in JavaScript to parse tags from a Docker image?

I recently came across this regex for parsing docker image tag in Python. ^(?P<repository>[\w.\-_]+((?::\d+|)(?=/[a-z0-9._-]+/[a-z0-9._-]+))|)(?:/|)(?P<image>[a-z0-9.\-_]+(?:/[a-z0-9.\-_]+|))(:(?P<tag>[\w.&bs ...

Unable to access the uploaded file on the server

Scenario : When a user uploads an image and clicks on the "save" button, I successfully save the image on the server with 777 permission granted to the folder... Problem : However, when I try to open the image, it does not display properly: Image url H ...

Uploading Files within Angular FormArray

I am facing an issue with my formArray which contains file upload inputs in each element. Whenever I upload an image in one input, it changes the values of other file inputs in different rows. https://i.stack.imgur.com/3haZW.png Current Behavior: Uploadi ...

Using jQuery to target the element before

Is there a way to determine the width of elements located before an element when it is hovered over? I attempted to achieve this using the following code: $('ul li').hover(function() { $(this).prevAll().each(function() { var margin = $(this ...

Having issues with AngularJS rzslider failing to dispatch updated slider value

Hello, I am currently using the rzmodule/rzslider in AngularJS. However, after changing the slider to a specific range, the ng-modal is not returning the updated value. It keeps returning the initial value of 10000 that was configured initially. $scope.sl ...

The ion-slide-box does not update after the active-slide has been changed using $index

I'm currently facing an issue with the controller that corresponds to this specific view. .controller('MenuCtrl', ['$rootScope','$scope','$state','$timeout','$ionicSlideBoxDelegate', functio ...