The code is functioning properly and executing without issues, yet I am puzzled as to why an error message is appearing in the console stating "Uncaught TypeError: Cannot read properties of null (reading 'style')"

Hey there, I'm new to the world of JavaScript and trying my hand at creating multiple modals that pop up. Everything seems to be working fine when opening and closing each modal, but I keep encountering an error message in the console (Uncaught TypeError: Cannot read properties of null (reading 'style')) when trying to close them. It's been a real struggle for me to figure it out :(. Can someone please take a look at the code below and help me correct it? Any assistance would be greatly appreciated!

HTML

I've used images as buttons for this.

let imageButtons = document.querySelectorAll('img[data-modal], span.close');
let modals = document.querySelectorAll('.modal');

function openModals(id) {
  let targetModal = document.getElementById(id);
  targetModal.style.display = "block";
}

function closeModals() {
  modals.forEach(modal => {
    modal.style.display = "none";
  });
}

imageButtons.forEach(button => {
  button.addEventListener('click', event => {
    closeModals();
    openModals(button.dataset.modal);
  });
});

modals.forEach(modal => {
  let closeButton = modal.querySelector('.close');
  closeButton.addEventListener('click', closeModals);
});
.modal {
  display: none;
  position: fixed;
  z-index: 1;
  padding-top: 100px;
  top: 0;
  left: 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: #78909C;
  margin: auto;
  padding: 0;
  border: 1px solid white;
  border-radius: 10px;
  width: 50%;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
}

.close {
  color: white;
  float: right;
  font-size: 20px;
}

.close:hover,
.close:focus {
  color: #bbb;
  cursor: pointer;
}

.modal-header {
  padding: 2px 16px;
  color: white;
  text-align: center;
}

.modal-header h2 {
  padding-top: 20px;
}

.modal-body {
  padding: 2px 16px;
  background-color: white;
  margin: 20px;
  border-radius: 10px;
}
<!-- Multiple Image Butto --> <div class="image-slider fade"> <img src="img/1.png" alt="image" data-modal="project1"> <p>Image 1</p> </div> ... (The rest of the HTML code continues here) </div>

Answer №1

The issue lies with the close button functionality. Although all other buttons are functioning correctly, you neglected to include the

dataset-modal="projectX"
attribute on the close button. As a result, when the openModal() function is called, the id is not being passed properly.

<span class="close" dataset-modal="projectX">&times;</span>

Adding this attribute to each of your modals should resolve the problem.

To troubleshoot this issue, I inserted a console log into the problematic function. I observed that while opening the modal using regular buttons worked fine, closing it using the "X" button triggered the error. It's crucial to understand the functions being called in your code. Using more descriptive variable names instead of generic ones like a can be beneficial.

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

Exploring directory organization in GraphQL Queries using GatsbyJS

In my portfolio, I have organized my work into categories, pieces, and pictures in a cascading order similar to a child-parent relationship. The folder structure reflects this hierarchy, with the main problem being explained in more detail below. Folder s ...

Incorporating Vuetify into a Vue CLI application with the help of webpack

I am facing an issue with my Vue CLI application that uses Webpack and Vuetify. The Vuetify components are not loading properly, and I keep getting the following warnings: Unknown custom element: < v-app > - did you register the component correctly? ...

Square-shaped picture with Bootstrap 4 design

I need help making images of different sizes appear as squares in a preview on my webpage. /* This is the CSS code which sets automatic height: */ .preview-img { width: 100%; height: auto; object-fit: cover; } How can I adjust the image height bas ...

What is the method for incorporating opacity into the background color CSS attribute using a Fluent UI color?

Currently, my challenge involves applying opacity to a background color sourced from the fluent UI library, which utilizes Design Tokens. Typically, I would add opacity to a background color like this: background-color: "rgba(255, 255, 255, 0.5)" However ...

Stop a form field from being visible on the screen

I'm working on a project where I would like to hide the user field in the form. models.py class Questions(models.Model): user=models.ForeignKey(User) category=models.ForeignKey(Categories) question=models.TextField(max_length=500) cr ...

Turn off the validation of individual JavaScript errors in Eclipse

Currently, I am exploring the use of Eclipse for JavaScript within the "Eclipse IDE for Java EE Developers" package. In my project, there is a heavy reliance on Bluebird, a promises implementation, resulting in several lines like: somePromise.catch(funct ...

How can I create a unique CSS or JS transition for a button that dynamically changes size based on text

My Angular app features a button labeled with "+". When the user hovers over it, I use element.append(' Add a New Number'); to add the text "Add a New Number" next to the + sign in the label. Upon clicking the button, a new number is added and ...

Tips for maximizing the benefits of debounce/throttle and having a truly dynamic experience

Attempting to implement a similar concept in Vue: props(){ debouncing: {type: Number, default: 0} }, methods: { clicked: _.debounce(function() { this.$emit('click'); }, this.debouncing), } Unfortunately, the code breaks when ...

Inserting data into a JavaScript database

When attempting to add a new row to a datatable and submit it to a JSP for database insertion, an error is encountered. The error message reads: "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the r ...

Executing a query with a `has many` relationship in MongoDB: Step-by-step guide

In my setup with Node, Express, and backbone, I am successfully retrieving records from MongoDB collections using simple queries. However, I am struggling to understand how to query more complex data, such as the one below: db.employees.aggregate( [ ...

Steps for validating the correct number of parameters passed to a function

Currently, I am developing a program with TypeScript and TSLint serving as the linter. Below is my preferred list of rules found in tslint.json: { "extends": "tslint:recommended", "rules": { "comment-format": [false, "check-space"], ...

Solve the issue with the horizontal scrollbar in Internet Explorer 7

The appearance of a horizontal scroll on this site in ie7 is quite puzzling. It functions perfectly in all other browsers, so I'm at a loss as to why this issue specifically arises in Internet Explorer 7. Any help in solving this problem would be grea ...

Break up a line within an ionic element by inserting a linebreak tag

Currently, I am constructing an app using ionic framework and facing a challenge in inserting a linebreak within an ionic tag to ensure proper display inside the designated container... <h2>{{caravan.model}}</h2> ...

What is the best way to retrieve the content of a file and set it as the value

exam.php <div class='btitle'>LOREM</div> main.php <?php $content = file_get_contents('exam.php'); ?> <textarea class='txa' value = <?php echo $content; ?>></textarea> outcome text ...

Perform simple arithmetic operations between a number and a string using Angular within an HTML context

I'm stuck trying to find a straightforward solution to this problem. The array of objects I have contains two values: team.seed: number, team.placement: string In the team.placement, there are simple strings like 7 to indicate 7th place or something ...

Obtaining the XPath for a data table containing two td elements that can be simultaneously clickable

<div class="dataTables_scrollBody" style="position: relative; overflow: auto; height: 370px; width: 100%; min-height: 0px;"> <table id="offer_create" class="display article-list ranklist_drag table table-bordered dataTable no-footer" aria-describe ...

Adjusting webpage background with JavaScript

I've been struggling with this for the past six hours and can't seem to get it right. I've checked out various solutions on Stack Overflow, but nothing seems to work. What am I missing here?!? My html5 page doesn't have a background an ...

A Guide to Implementing v-for in a JSON Array with Vue.js

After receiving JSON data from the server: [ {"id":"2","name":"Peter","age":"24"}, {"id":"4","name":"Lucy","age":"18"}, ] I am ...

Pass data to JavaScript using Node.js Express server

I recently started learning nodejs and have encountered a challenge in sending a variable from my nodejs express server to a javascript file. The code I currently have is: res.send(String(playerLives)); The variable playerLives is an integer, and I faced ...

Feature exclusively displays malfunctioning image URLs for the web browser

Hello everyone! I've been diving into learning JavaScript and recently attempted to create a function that randomly selects an image from an array and displays it on the browser. Unfortunately, despite my efforts, all I see are broken link images. Her ...