A step-by-step guide on closing a Bootstrap 5 Modal using JavaScript

Objective:
I am trying to close a bootstrap 5 modal using JavaScript code after showing an alert message.

Challenge:
I am facing difficulty getting the function myFunction to work and subsequently closing the modal once the alert message is displayed using JavaScript code.

Details:
*The 'data-bs-dismiss="modal"' attribute should not be used.

JSBIN:
https://jsbin.com/sileqajiho/edit?html,js,output

Thank you!


<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="64060b0b10171016051424514a554a57">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet">
  <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="32505d5d46414640534272071c031c031f">[email protected]</a>/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>

<div class="container mt-3">
  <h3>Modal Example</h3>
  <p>Click on the button to open the modal.</p>
  
  <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#myModal">
    Open modal
  </button>
</div>

<!-- The Modal -->
<div class="modal" id="myModal">
  <div class="modal-dialog">
    <div class="modal-content">

      <!-- Modal Header -->
      <div class="modal-header">
        <h4 class="modal-title">Modal Heading</h4>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>

      <!-- Modal body -->
      <div class="modal-body">
        Modal body..
      </div>

      <!-- Modal footer -->
      <div class="modal-footer">
        <button type="button" class="btn btn-danger" onclick="myFunction()" >Start</button>
      </div>

    </div>
  </div>
</div>

<script>

  function myFunction() {
    alert("test")
  }
  
<script>


</body>
</html>

var myModal = document.getElementById('staticBackdrop');
var modal = bootstrap.Modal.getOrCreateInstance(myModal)
modal.show()

Answer №1

https://example.com/jsbin-edit-html-js-output


<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Sample</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://cdn.example.com/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>

<div class="container mt-3">
  <h3>Popup Example</h3>
  <p>Click on the button to show the popup.</p>
  
  <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#myModal">
    Open popup
  </button>

</div>

<div class="modal" id="myModal">
  <div class="modal-dialog">
    <div class="modal-content">

      <div class="modal-header">
        <h4 class="modal-title">Popup Heading</h4>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>

      <div class="modal-body">
        <button type="button" onclick="closePopup()">Close Popup with script</button>

      </div>

      <div class="modal-footer">
        <button type="button" class="btn btn-danger" onclick="startFunction()">Start</button>
      </div>

    </div>
  </div>
</div>

<script src="https://cdn.example.com/dist/js/bootstrap.bundle.min.js"></script>
<script>
  
  function closePopup() {
    alert("Closing popup");
    modalInstance.hide()
  }
  
</script>  
  
  
</body>
</html>

-------------

var modalInstance = null;
var modelElem = document.querySelector('#myModal');
modelElem.addEventListener('shown.bs.modal', function (){
  modalInstance = bootstrap.Modal.getInstance(modelElem);
});

Answer №2

To implement Bootstrap 5.0, you can utilize this code:

        let modalElement = document.getElementById('myModal')
        let modalInstance = bootstrap.Modal.getInstance(modalElement)
        modalInstance.hide()

Answer №3

From what I understand, the usage of new is required in this scenario. Here is a demonstration of creating a toast:

var myToast = new bootstrap.Toast(toastDiV, opts)
myToast.show()

Since they are class objects, a new instance must be referenced.

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 the button is clicked, request the total count of elements in the array

Is there a way to log the index of an array element when clicked? I have a large array with over 100 elements: var cubesmixed = []; var cubes; for(var i = 0; i < 143; i++) { cubes = paper.rect(Math.floor(Math.random()*2000), Math.floor(Math.random ...

Elusive shadow fails to appear in ThreeJS scene

<style> body { margin: 0; } </style> <script async src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0267712f6f6d66776e672f716a6a6f716a6f717a333c343c71">[email protec ...

What is the best way to store data from multiple selected rows in different datagrids into a single state?

Programming Languages : JavaScript with React, Redux Toolkit, and Material-UI Issue : My goal is to synchronize the selection of checkboxes across multiple datagrids into one central state Attempts Made : I first attempted to manage checkbox selection fo ...

Using Slick.JS to Sync Navigation with Main Slider, Automatically Resetting to First Slide

I have a question about the functionality of the Slick.JS plugin that I'm using. In my project, I have two carousels with five slides each. The top carousel displays one slide at a time, while the bottom carousel shows all five slides concurrently. My ...

Animate CSS during page load

Currently, I am implementing AJAX to dynamically load pages on my website. During the loading process, I wish to incorporate a spinning animation on the logo to indicate that content is being fetched. The jQuery script (although I'm still learning an ...

The stylesheet is linked, but no changes are taking effect

I've linked my template.php to style.css, and when I make changes in template.php, they show up fine. However, if I make changes in the stylesheet, nothing happens. What should I do? My website is not live; I'm working on it using a WAMP server. ...

Error in NodeJS session: the variable "request" is not defined

Recently, I have started working with NodeJS and I am currently facing an issue while trying to implement sessions in my project. Any assistance or guidance on this matter would be greatly appreciated. Below is the code snippet where the error occurs: va ...

Building a table in Quasar by utilizing nested objects

I am currently facing an issue while using Quasar to create Q-Tables. I am struggling with incorporating nested objects with dynamic key names. Below is the content of my table: data: [ { 'FrozenYogurt' : { &a ...

Utilizing Custom Script Tag Types in Visual Studio for Enhanced HTML Template Functionality and Improved Syntax Highlighting

Currently, I am utilizing Visual Studio 2012 for editing HTML and JavaScript. My approach involves inserting templates using partial views in inline script tags (view code below). The use of AngularJS, a Javascript framework, dictates that the type must be ...

Setting the Height of a Fixed Element to Extend to the Bottom of the Browser Window

I currently have a webpage layout featuring a header at the top, a fixed sidebar on the left side, and main content displayed on the right. A demo version of this layout can be viewed at http://jsbin.com/iqibew/3. The challenge I'm facing is ensuring ...

Gather input from a form and store it in an Object upon submission

I am facing a challenge as I do not have much experience with object-oriented JavaScript. My goal is to have a form submit details such as the first and last name to an object that I've created. Here is the object I have: function Person(firstName, ...

Pass a PHP string to a JavaScript function using AJAX

Recently, I encountered an issue with my database storing email content. To retrieve this content, I made an ajax request and wanted to pass the data to a function that would display a popup with the email content. However, the email content contains HTML ...

AngularFire - Structuring item references for child templates using ng-repeat

I have been struggling with this issue for hours and can't seem to find a solution. In my dashboard, all data from my Firebase database is visible using Ng-repeat. However, I am trying to select a specific item and view its details on another page. H ...

Ways to retrieve a grandchild element of a specific element using its tag name

I'm struggling to access elements that are nested within various levels of parent elements with and without IDs. The usual method getElementByTagName doesn't seem to be working for me, especially when the target element is three levels deep. Is t ...

I am looking to host several iterations of jQuery on a content delivery network within my Nuxt application

Currently, we are loading jQuery 3.1.4 externally from a CDN on the top page. index.vue head: { bodyAttrs: { id: 'overview' }, script: [ { src: 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min ...

Struggling to devise a for loop for a JavaScript-generated list

I'm attempting to loop the content of an H1 element through a list 10 times. I seem to have made a mistake in my code and would appreciate any guidance. var headOne = document.createElement("H1"); headOne.textContent = "Hello World"; document.body. ...

How can I add text to the title of a border using Bootstrap5?

I am attempting to create a design where text appears within the border of an element. I am currently utilizing Bootstrap 5 and jQuery for this project. Despite my efforts with fieldset and legend elements, I have not been successful in achieving the desir ...

Is it considered fundamentally inappropriate to call $scope.$digest within $scope.$on?

I recently inherited some AngularJS code, and my knowledge of both the codebase and Angular itself is limited. Within the code I inherited, there are instances where $scope.$digest is being called inside a $scope.$on method within a controller. Here's ...

Unveil concealed information within a freshly enlarged container

As I organize my content into an FAQ format, I want users to be able to click on a link and expand the section to reveal a list of items that can also be expanded individually. My goal is to have certain list items expand automatically when the FAQ section ...

Utilize the dimensions of one image to resize others using the JavaScript method .getBoundingClientRect

I am attempting to transfer the width and height measurements of the initial image to all subsequent images on the page. Currently, I have successfully applied the dimensions of the first image to the second one, but I am facing difficulties with the thir ...