JavaScript Error: Uncaught TypeError - The property 'remove' cannot be read because it is undefined

My modal window setup allows for opening two separate modals one after another, with the capability to close them individually (closing the second modal while keeping the first one active).

(All the necessary code snippets are included below)

let open_modals = [];

$(function () {

  // Get the button that opens the modal
  var btn = document.querySelectorAll(".modal-button");

  // All page modals
  var modals = document.querySelectorAll('.modal');

  // Get the <span> element that closes the modal
  var spans = document.getElementsByClassName("close");

  // Opening the modals on button click
  for (var i = 0; i < btn.length; i++) {
    btn[i].onclick = function (e) {
      e.preventDefault();
      modal = document.querySelector(e.target.getAttribute("href"));
      modal.style.display = "block";
      open_modals.push(modal.id);
    }
  }

  // Closing the modals by clicking on the close button
  for (var i = 0; i < spans.length; i++) {
    spans[i].onclick = function () {
      for (var index in modals) {
        if (typeof modals[index].style !== 'undefined' && modals[index].id == open_modals[open_modals.length - 1]) {
          modals[index].style.display = "none";
          open_modals.pop();

          setTimeout(function () {
            for (var index in modals) {
              modals[index].classList.remove("modal-content-active");
              modal.style.display = "none";
              open_modals.pop();
            }
          }, 400);
        }
      }
    }
  }

  // Closing the modal by clicking anywhere outside it
  window.onclick = function (event) {
    if (event.target.classList.contains('modal')) {
      for (var index in modals) {
        if (typeof modals[index].style !== 'undefined' && modals[index].id == open_modals[open_modals.length - 1]) {
          modals[index].style.display = "none";
          open_modals.pop();

          setTimeout(function () {
            for (var index in modals) {
              modals[index].classList.remove("modal-content-active");
              modal.style.display = "none";
              open_modals.pop();
            }
          }, 400);
        }
      }
    }
  }
})
Insert custom CSS here...
Add external script tag and html structure for modal windows here...

When attempting to close my modal window, I encountered an error message as mentioned in the title. Removing specific lines from the JavaScript code resolved the issue temporarily, but those lines are essential for animation purposes.

If anyone has any suggestions for fixing this problem without skipping the animation feature, please let me know. Thank you!

Answer №1

const active_modals = [];

$(function () {

  // Select all elements with the class "modal-button"
  const btn = document.querySelectorAll(".modal-button");

  // Get all modals on the page
  const modals = document.querySelectorAll('.modal');

  // Get the <span> element that closes the modal
  const spans = document.getElementsByClassName("close");

  // Open the modal when the button is clicked
  for (let i = 0; i < btn.length; i++) {
    btn[i].onclick = function (e) {
      e.preventDefault();
      const modal = document.querySelector(e.target.getAttribute("href"));
      modal.style.display = "block";
      active_modals.push(modal.id);
    }
  }

  // Close the modal when the <span> is clicked
  for (let i = 0; i < spans.length; i++) {
    spans[i].onclick = function () {
      for (var index in modals) {
        if (typeof modals[index].style !== 'undefined' && modals[index].id == active_modals[active_modals.length - 1]) {
          modals[index].classList.add("modal-content-active");
          const item = modals[index];
          setTimeout(function () {
            item.classList.remove("modal-content-active");
            item.style.display = "none";
            active_modals.pop();

          }, 400);
        }
      }
    }
  }

  // Close the modal when clicked outside of it
  window.onclick = function (event) {
    if (event.target.classList.contains('modal')) {
      for (let index in modals) {
        if (typeof modals[index].style !== 'undefined' && modals[index].id == active_modals[active_modals.length - 1]) {
          modals[index].classList.add("modal-content-active");
          const item = modals[index];
          setTimeout(function () {

            item.classList.remove("modal-content-active");
            item.style.display = "none";
            active_modals.pop();

          }, 400);

        }
      }
    }
  }
})

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

Replace Euro symbols in JavaScript Regexp with grouping

Need assistance creating a Regex pattern for &#8203; € 14,50. After the replacement is completed, only 14,50 Can anyone provide guidance? ...

Error: Attempting to access 'scrollTop' property of null object in Material UI library

After updating from MUI-4 to MUI-5, I encountered this error. Can anyone provide assistance? ...

I'm just getting started: an image carousel featuring a unique twist with random quote overlays, but there's a catch - it only activates on the very first image... what comes next?

After successfully displaying the generator over the first image, I encounter a problem with the second and third images where it seems to disappear. However, upon cycling back to the first slide, the generator reappears with a different quote. I've a ...

Production build encountering unhandled TypeError in proxy

One day, I decided to tweak MUI's styled function a bit, so I came up with this proxy code: import * as muiSystem from '@mui/system'; type CreateMUIStyled = typeof muiSystem.styled; type MUIStyledParams = Parameters<CreateMUIStyled>; ...

Form on the internet with a following button

Currently working on a basic form: <tr> <td> <label for="FirstName">First Name <span class="req">*</span> </label> <br /> <input type="text" name="FirstName" id="FirstName" class="cat_textbox" ...

Create interactive highcharts graphs using data from a CSV file generated through PHP

I'm having trouble working with Highcharts and csv data. Take a look at this example: http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/line-ajax/ $.getJSON('http://www.highcharts.com/ ...

Ensure that only the most recent Ajax request is allowed

In my project, I have an input box that triggers an ajax request with every key press. This means if I type the word "name," there will be a total of 4 requests sent out. However, what I really need is to only execute the latest request. So even if I enter ...

The Bootstrap dropdown menu is cut off and not fully visible on mobile devices

I am experiencing an issue with the mobile version of a website where the dropdown menu is not fully visible due to the position of a specific menu item and the number of items in the dropdown. https://i.sstatic.net/HmXeq.png The image below shows how I ...

Troubleshooting Issue with Nested ng-include in AngularJS: Difficulty arises when the parent element with the ng-include attribute is dynamically added using the ng-

Click here to see a demo plunker that will help you understand my issue. On my main page, I have a table. Each table row is followed by a hidden empty row. When the first row is clicked, I use a directive to inject HTML into the empty row below it. Main ...

Creating specialized validation for numeric fields in Angular2

Attempting to implement custom validation in Angular 2 has been a challenge for me. I have followed the necessary steps based on my understanding, but still struggling to get it working. import { FORM_DIRECTIVES, AbstractControl, ControlGroup ,FormBuilder ...

Place a pair of divs in the center next to one another

What is the best way to align two divs in the center beside each other with some padding in between that actually works? I attempted using display: inline, but it didn't have the desired effect. .my-container { position: rela ...

The value of req.file is not defined by multer

I'm at my wit's end with this issue. Despite searching extensively, none of the proposed solutions have resolved it for me. I am attempting to set up a basic file upload using multer, but I cannot seem to make it work as req.file consistently rem ...

The Bootstrap 4 Carousel Indicators are missing from the page

I am currently working on creating a carousel slider with indicators at the bottom using Bootstrap 4.1.3. However, I have run into an issue where the indicators are not visible, although they still function when clicked on. I have attempted solutions such ...

Are box shadows displaying different hues across various web browsers?

Yesterday, I came across a minor issue with my website. The Box-Shadows appear differently on various browsers. Previously, it was red on Firefox and IE, but now it looks completely different on: Opera: Orange Chrome: Violet Safari: Blue Why is that hap ...

As the screen width shrinks, I've noticed that my grid system in HTML using Bootstrap starts to glitch

Why is my row going onto a second line when I shrink the width? Here is a screenshot of the issue. I am currently using bootstrap 5 for this and I am unsure how to fix it. Below is the code snippet: Current Screenshot Below is the desired look on mobil ...

Achieving effective targeting of the second segment within a string enclosed in a span tag through increased specificity

When it comes to styling elements, the easiest way is to use classes and assign the properties needed. However, 1. I'm not a huge fan of creating classes all over the place. That's what specificity and CSS mapping are for. 2. Going thro ...

Inconsistent rendering issue identified in AngularJS when updating arrays with ui-router

I'm leveraging ui-router to navigate to specific subpages in my application: var myApp = angular.module("myApp",['ui.router']); myApp.config(function($stateProvider, $urlRouterProvider) { $stateProvider .state('usergroups&apos ...

Jquery ripple effect does not function properly with background-attachment: fixed style

Is there a way to make the effect ripples () work with background-attachment: fixed? I'm trying to achieve this effect while keeping the background fixed in place. Any suggestions on how to make this work? background-attachment: fixed; ...

Fixing the department display list in React Hook: A step-by-step guide

{ roomDept.map((item, index) => ( <div key={index} className="flex flex-col pb-2 items-center"> <div className="flex pb-2 w-full"> <SelectPick ...

jQuery fails to modify HTML according to its intended purpose

I've been struggling to update a price using JQuery. Even though the code seems fine when I check the console, the HTML doesn't reflect the changes. Additionally, when I try to log console.log(newPrc), it gives an error saying "newPrc" is not def ...