The addEventListener feature in Bootstrap 5.2.3 seems to be malfunctioning

I have a sample page with a Bootstrap dialog being returned from the server. I want to display it inside a DIV.

However, when clicked, I receive this error:

Uncaught TypeError: myModal.addEventListener is not a function

It points to this line of code:

myModal.addEventListener('show.bs.modal', function () {

Any ideas why? Thank you!

<head>
  <meta charset="utf-8">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="086a67667d7a7d796a41423d263a263b">[email protected]</a>/dist/css/bootstrap.min.css" type="text/css" />
</head>

<body>
  <p><a href="#" onclick="showSubscriptionInfo();">Open dialog</p>
     <div id="myDiv"></div>
   </body>
   
   <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ed8f8282999e999f8c9dadd8c3dfc3de">[email protected]</a>/dist/js/bootstrap.bundle.min.js"></script> 
   <script>
   function showSubscriptionInfo(){
     var data = ''+
      '<div class="modal fade" id="subsModal" tabindex="-1" aria-labelledby="exampleModalLabel">'+
      '  <div class="modal-dialog">'+
      '    <div class="modal-content" style="height:450px">'+
      '      <div class="modal-body">'+
               '<p>xxx</p>'+
      '      </div>'+
          '<div class="modal-footer">'+
          '  <button type="button" class="button" data-bs-dismiss="modal">Close</button>'+
          '</div> '+
      '    </div>'+
      '  </div>'+
      '</div>';
    
     document.getElementById('myDiv').innerHTML = data;
     var myModal = new bootstrap.Modal(document.getElementById('subsModal'));
     myModal.show();
     
     myModal.addEventListener('show.bs.modal', function () {
       alert(1);
     }, { once: true });
     myModal.addEventListener('hide.bs.modal', function () {
       alert(2);
     }, { once: true });
     
   }
   </script>

Answer №1

Tracking events in bootstrap modals should be done on the div used to create the modal (

document.getElementById('subsModal')
) rather than on the bootstrap.Modal object (
new bootstrap.Modal(document.getElementById('subsModal'))
).

For more information, refer to the modal documentation and modal event documentation.

function showSubscriptionInfo() {
  var data = '' +
    '<div class="modal fade" id="subsModal" tabindex="-1" aria-labelledby="exampleModalLabel">' +
    '  <div class="modal-dialog">' +
    '    <div class="modal-content" style="height:450px">' +
    '      <div class="modal-body">' +
    '<p>xxx</p>' +
    '      </div>' +
    '<div class="modal-footer">' +
    '  <button type="button" class="button" data-bs-dismiss="modal">Close</button>' +
    '</div> ' +
    '    </div>' +
    '  </div>' +
    '</div>';

  document.getElementById('myDiv').innerHTML = data;
  var subsModal = document.getElementById('subsModal');
  var myModal = new bootstrap.Modal(subsModal);
  subsModal.addEventListener('show.bs.modal', function() {
    alert(1);
  }, {
    once: true
  });
  subsModal.addEventListener('hide.bs.modal', function() {
    alert(2);
  }, {
    once: true
  });

  myModal.show();
}
<!DOCTYPE html>
<html lang="en>

<head>
  <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5e3c31312a2d2a2c3f2e1e6b706d706f">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-4bw+/aepP/YC94hEpVNVgiZdgIC5+VKNBQNGCHeKRQN+PtmoHDEXuppvnDJzQIu9" crossorigin="anonymous"gt;
  <script src="https://cdn.jsdelivr.net/npm/@popperjs/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c0a3afb2a580f2eef1f1eef8">[email protected]</a>/dist/umd/popper.min.js" integrity="sha384-I7E8VVD/ismYTF4hNIPjVp/Zjvgyol6VFvRkX/vR+Vc4jQkC+hVqc2pM8ODewa9r" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1d7f7272696e696f7c6d5d28332e332c">[email protected]</a>/dist/js/bootstrap.min.js" integrity="sha384-Rx+T1VzGupg4BHQYs2gCW9It+akI2MM/mndMCy36UVfodzcJcF0GGLxZIzObiEfa" crossorigin="anonymous"></script>
  <meta charset="utf-8">
  <link rel="stylesheet" href="css/bootstrap.min.css" type="text/css" />
</head>

<body>
  <p><a href="#" onclick="showSubscriptionInfo();">Click HERE</a></p>
  <div id="myDiv"></div>
</body>
<!-- script src="js/bootstrap.bundle.min.js"></script -->
</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

When utilizing getServerSideProps, the data is provided without triggering a re-render

Although my approach may not align with SSR, my goal is to render all products when a user visits /products. This works perfectly using a simple products.map(...). I also have a category filter set up where clicking on a checkbox routes to /products?catego ...

When you're downloading a file in Safari, the filename ends up being displayed as 'unidentified'

I am encountering an issue with the code I implemented that downloads a file in Safari, but the filename appears as 'untitled'. Interestingly, it works fine in other browsers. var saveData = (function () { var base64 = "data:application/mswo ...

Can you explain the distinction between the "DOMContent event" and the "load event"?

Within Chrome's Developer tool, there is a blue vertical line marked "DOMContent event fired", as well as a red line labeled "load event fired". Is it safe to assume that the "DOMContent event fired" signifies the initiation of inline JavaScript execu ...

Transferring PHP array to JavaScript with the help of AJAX

I've been working on integrating Google Maps and Instagram in a project of mine. My main challenge is figuring out how to pass the coordinates of Instagram photos from my PHP file to my JavaScript file using AJAX. I'm quite lost when it comes to ...

Tips for passing an object as an argument to a function with optional object properties in TypeScript

Consider a scenario where I have a function in my TypeScript API that interacts with a database. export const getClientByEmailOrId = async (data: { email: any, id: any }) => { return knex(tableName) .first() .modify((x: any) => { if ( ...

a stand-alone Node.js application connecting to a self-signed WebSocket (WSS) server

I am currently working with a node server (Meteor.js) that needs to communicate with another server using websockets. Since the communication is strictly between servers and does not involve direct users, I have decided to use a self-signed certificate. I ...

How can I display the Bootstrap 5.3.0 Collapsible button on this basic website?

I've been struggling to implement a Bootstrap Collapsible on my web page using Bootstrap version 5.3.0. I've tried different approaches but I can't seem to get it to work. All I need is a Collapsible that contains a few links, which should b ...

Why does React / NextJS throw a "Cannot read properties of null" error?

In my NextJS application, I am using useState and useEffect to conditionally render a set of data tables: const [board,setBoard] = useState("AllTime"); const [AllTimeLeaderboardVisible, setAllTimeLeaderboardVisible] = useState(false); const [TrendingCreat ...

Is there a way to retrieve data from a sealed JSON object using JavaScript?

The data is being fetched from the API and here is the response object: { "abc": [{ "xyz": "INFO 1", "pqr": "INFO 2" }, { "xyz": "INFO 3", "pqr": "INFO 4" } ] } We are lookin ...

What is the best way to disable the functions doajax_red and doajax_blue when a radio button is checked?

Is there a way to halt the functions doajax_red and doajax_blue when a radio button is checked? Upon loading the page index.php, clicking the red button will display a loading image. If you check the BLUE radio button and then re-check the RED radio butt ...

Tips for integrating CSS with Material UI TableContainer

I have utilized Material UI Grid to display data in a chart. However, the appearance of the chart does not match my expectations. Instead of resembling the desired "dense table," it looks different: Actual Look of the Chart Below is the code snippet I ha ...

Switching elements in an array using Vue.js

Within my vue.js web application, I am attempting to switch the positions of two rows in a forum. Below is the code snippet I am using: export default { data() { return { forums: [] } }, met ...

Looking to restrict the data retrieved from an API while utilizing ReactJS

I am currently fetching transaction data from an API. One of the fields in the response is buyer, which may sometimes be null. As a result, I am excluding any entries with a null buyer. This leads to varying numbers of results being displayed. My goal is t ...

Removing single quotes and replacing them with spaces when passing data from JavaScript to MySQL

I'm currently focused on JavaScript using Hapi.js in my role at the company. My main task involves retrieving data from MongoDB and transferring it to a MySQL database. The challenge arises when dealing with data that contains single quotes within th ...

Sharing Data Between Controllers in AngularJS

I am faced with a challenge involving two Angular controllers: function Ctrl1($scope) { $scope.prop1 = "First"; } function Ctrl2($scope) { $scope.prop2 = "Second"; $scope.both = Ctrl1.prop1 + $scope.prop2; //Ideally, I would like to achieve t ...

"Utilizing Javascript in an ERB view file within the Rails framework

In my .js.erb file, I need to execute a conditional statement when an ajax call is triggered. Below is the code snippet: function updateContent() { $('.organiser__holder').html('<%= escape_javascript render("filter_links") %>' ...

Tips for retrieving return values from an ajax form submission

When using ajax to submit a form, I encountered an issue where the process would halt at api.php and not return to the ajax success. Below is the code snippet: <form method="POST" id="form_1" action="../api.php" enctype="multipart/form-data" novalidate ...

Retrieve all posts from a specific category on a WordPress website using Node.js

Is there a way to retrieve all articles from the "parents" category on a WordPress website without just getting the html of the page? I need the full text of each article, not just a link with a "read more" button. I have tried using the nodejs plugin "w ...

Passing parent HTML attributes to child components in Angular 2

Is there a way to pass HTML attributes directly from parent to child without creating variables in the parent's .ts class first? In the sample code below, I am trying to pass the "type=number" attribute from the parent to the app-field-label component ...

Analyzing the audio frequency of a song from an mp3 file with the help of HTML5 web audio API

Currently, I am utilizing the capabilities of the HTML5 web audio API to detect when a song's average sound frequency drops below a specific threshold and create corresponding markers. Although I have successfully implemented this using AudioNodes, th ...