Unable to dismiss modal box by using the close button or clicking outside of it

I recently started learning Javascript and I'm trying to implement modal boxes for profile information on a drag-and-drop website. While I have successfully managed to open all the modals, there seems to be an issue with closing them consistently. The code below is embedded in the HTML section of a drag-and-drop platform, and although I have refrained from using global JavaScript so far, I am willing to explore that option if needed. Any advice or suggestions are greatly appreciated.

<style>
.card { 
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
  max-width: 300px; 
  margin: auto; 
  text-align: center; 
  font-family: arial; 
  background-color: #ffffff;
}

.title {
  color: grey;
  font-size: 18px;
}

button { 
  border: none; 
  outline: 0; 
  display: inline-block; 
  padding: 8px; 
  color: white; 
  background-color: #333192; 
  text-align: center; 
  cursor: pointer; 
  width: 100%; 
  font-size: 18px; 
} 

a { 
  text-decoration: none; 
  font-size: 22px; 
  color: black; 
}

button:hover, a:hover { 
  background-color: #1b1464; 
}

body {
  font-family: Arial, Helvetica, sans-serif; 
}

.modal { 
  display: none; 
  position: fixed; 
  z-index: 1; 
  padding-top: 12px; 
  left: 0;
  top: 0; 
  width: 100%; 
  height: 100%;
  overflow: auto; 
  background-color: rgb(0,0,0); 
  background-color: rgba(0,0,0,0.4); 
 }

.modal-content { 
  position: relative; 
  background-color: #FFFFFF; 
  margin: auto; 
  padding: 0px; 
  width: 80%; 
  box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19);
   -webkit-animation-name: animatetop;
   -webkit-animation-duration: 0.4s; 
  animation-name: animatetop;
  animation-duration: 0.4s; 
} 

@-webkit-keyframes animatetop { 
  from {top:-300px; opacity:0}
    to {top:0; opacity:1} 
}

@keyframes animatetop { 
  from {top:-300px; opacity:0} 
    to {top:0; opacity:1} 
}

.close { 
  color: white; 
  float: right; 
  font-size: 28px; 
  font-weight: bold; 
} 

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

.modal-header { 
  padding: 12px; 
  background-color: #333192; 
  color: F15C22; 
} 

.container { 
  position: relative; 
  width: 100%; 
} 

</style>

Contact

<div class="container">
  <div id="patricoloModal" class="modal">
    <div class="modal-content">
      <div class="modal-header">
        <span class="close">×</span>

     <h3 style="color:#F15C22">Francesca Patricolo</h3>
  </div>

  <div class="modal-body">
    // Modal body content here
  </div>

  <div class="modal-footer"></div>
</div>

<script type="text/javascript>
var modal = document.getElementById('patricoloModal'); 
var btn = document.getElementById("patricoloBtn"); 
var span = document.getElementsByClassName("close")[0]; 

btn.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

Eliminate the usage of Javascript to display the Modal, as this method is not recommended.

Substitute the following code:

<a id="patricoloBtn"><img src="path" alt="Francesca" class="image" style="width:100%"></a>

with

<a data-toggle="modal" data-target="#patricoloModal"><img src="path" alt="Francesca" class="image" style="width:100%"></a>

Answer №2

To implement event listeners on multiple elements, follow these steps:

var closeButtons = document.getElementsByClassName("close");
closeButtons.forEach(btn => btn.addEventListener("click", closeModal));

Here is the code snippet:

        /*** Access the modal***/
        var myModal = document.getElementById('myModal'); 
        /*** Access the button that triggers the modal ***/

        var openBtn = document.getElementById("openBtn"); 
         /*** Access the <span> element that closes the modal***/
        var closeButtons = document.getElementsByClassName("close"); 

        /*** Open the modal when the button is clicked***/ 
        closeButtons.forEach(btn => btn.addEventListener("click", closeModal));

        /*** Close the modal when the <span> (x) is clicked ***/
        function closeModal() {
            myModal.style.display = "none";
        } 
        /*** Close the modal when anywhere outside the modal is clicked***/
        document.body.addEventListener("click", (event)=>{

            // IF THE CLICKED TARGET IS NOT EQUAL TO THE MODAL
            if(event.target !== myModal) {
                myModal.style.display = "none";
            }
        })

I hope this solution helps you.

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

Frames of Animation

Seeking assistance in understanding how to create frame animation using JavaScript or CSS. Attempting to replicate the animation seen on this website. Intrigued by the road animation and unsure if it is achieved using a plugin or just JavaScript and CSS. ...

I'm a complete programming newbie and I want to start learning JavaScript, jQuery, and other programming languages. Where should I

Coming from a design background with zero programming knowledge, I have recently learned XHTML and CSS. Now, I am eager to expand my skills by mastering JavaScript, jQuery, and more. Where should I begin? This will be my first foray into programming. Whil ...

Combining Meshes in three.js LOD

I am searching for an efficient way to utilize the LOD Object from three.js (view example here). My concept involves creating an LOD method similar to the one outlined in chapter 2.1 (found here). The structure consists of 3 levels: a 3D model in close ...

The Node.js application is unable to execute due to the error: "View "error" could not be found in the views directory."

Currently, I am following a tutorial that covers the integration of social login with Passport and Node. You can find the tutorial here: Tutorial Link In line with the tutorial, I have started working on a project while utilizing Windows 10 operating syst ...

Java cookies are utilized to download a file using JavaScript

When I attempt to download a file using Java code, I receive HTML code instead of the actual file contents. Interestingly, if I directly visit the download URL in a browser, the file automatically downloads: <html> <body> <script type="text ...

Efficiently handling shared jQuery scripts in an ASP.NET development

Looking for guidance on utilizing javascript/jQuery snippets in an asp.net project. It is recommended to store all scripts in a separate file rather than inline, making it easier to manage and improve performance by spreading functions across multiple file ...

Using Node.JS, Sequelize, and Moment.JS to format dates

Seeking help on formatting a date loaded from Sequelize in my database. I'm working on a blog and need to display the creation date of an article. Here's my route: app.get("/", (req,res) =>{ Article.findAll({ order:[ [ ...

Error Message: Unexpected character "C" found in JSON response from Ionic 2 Http GET request

Trying to execute a GET request and extract data from the response. this.http.get('http://localhost:8888/maneappback/more-items.php').subscribe(res => { console.log(res.json()); }, (err) => { console.log(err); }); An error message ...

Pictures are automatically adjusted to a resolution of 0 x 0 within the Heroku application

I have encountered an issue with my simple webpage hosted on Heroku. Despite appearing perfectly fine on localhost, 4 images are automatically resized to 0x0 when viewed on Heroku. I am struggling to identify the cause of this problem. Here is how it appe ...

Passing and showcasing JSON information from one webpage to another upon clicking by utilizing local storage

I've been experimenting with a way to transfer JSON data from one page to another by using local storage. For instance, when a user clicks on a specific book image, they are directed to book.html where the image and book name are displayed (retrieved ...

Despite having installed NPM, the system is still unable to recognize the command, displaying the message: 'CALL "C:Program Files odejs ode.exe" "C:Program Files odejs ode_modules pmin pm-prefix.js"'

Having a problem with npm on my Windows computer. Whenever I type npm --version in the command line, I see the following message: C:\\Users\\nares\>npm --version 'CALL "C:\\Program Files\\nodejs&bso ...

The use of Physijs and implementing setLinearVelocity for object movement

2-09-2015 - UPDATE: The code provided below is now functional with the use of setLinearVelocity(). If you were facing similar issues, this updated code may help you. Find the original question with the corrected code below... A player object has been deve ...

Automatically adjust divs to fill available space

I've been grappling with a challenge involving my divs - how to translate my design seamlessly into the actual layout. Thus far, research and implementation have not yielded the desired results. In the link provided, you'll notice //PORTFOLIO fol ...

Input field with JQuery datepicker showing only months and years

I have encountered a question that closely resembles the one discussed here: year/month only datepicker inline The scenario I'm facing involves utilizing the input version instead of the div. In the case of using the div, the ui-datepicker-calendar ...

Showing the precise age in years by utilizing the provided 'Date of Birth' selected from the datePicker

Is it possible to retrieve the date entered in the datePicker and use it to populate the current age field in a PHP file using either PHP or Javascript? if ($key == 'currentage') { $group[] = $this->form->createEleme ...

Utilize JSON parsing to extract and store data into an object

I'm currently working on extracting specific objects from a parsed JSON stored within an object named data.json. var data = { json: '', text: '', welcome: '', q1: '', } let foo = await fetch(spr ...

What is the best way to display numerical data within an inline list format?

Here is a list I have: <ol> <li>Login</li> <li>Address</li> <li>Shipping</li> </ol> The numbers in the list display correctly as decimals. However, when I change the <li> tag to inline or ...

Error: Attempting to access the 'main' property of an undefined object - React dilemma

For my React webpage, I decided to create a theme using createMuiTheme from material-ui, and here is the palette I defined: palette: { primary: { main: "#333333" }, secondary: { main: "#727171" }, background: { paper: " ...

I am currently utilizing VScode and attempting to connect to an asset, but I noticed that two characters in the link appear yellow instead of orange. What could

Could the usage of a Bootstrap CDN be the reason for this issue? Although it was an easy fix, I am still curious. Was it caused by simply copying and pasting the code? ...

Monitor the Ajax for any updates in the database and trigger the code accordingly

My objective is to send requests to a php file with specific parameters in this format: <!DOCTYPE html> <html> <head> <script> function onsubmit() { var id = $_SESSION['user']['id']; var xmlhttp; if ...