Using vanilla JavaScript to close a modal in Bootstrap 5 is a great way

Hello, I recently came across a tutorial which discusses how to show a modal in Bootstrap 5 using JavaScript. The tutorial can be found at the following link: https://getbootstrap.com/docs/5.0/components/modal/#via-javascript. In the tutorial, they demonstrate using a button to toggle showing the modal. To display a modal with JavaScript in Bootstrap 5, you would typically use the following code snippet:

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

My question is regarding closing a modal with JavaScript that was opened using a button. Essentially, how can I retrieve a reference to the modal that was previously opened? Once I have access to this reference, I would simply call the .hide() method on it.

-- Edit -- To clarify, in Bootstrap 5 when a modal is opened without using JavaScript, the following HTML structure is typically used:

<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal">
  Launch demo modal
</button>

I have been attempting to obtain a handle to this modal for further interactions.

Answer №1

Finally cracked the code.

const modalElement = document.getElementById('staticBackdrop');
const myModal = bootstrap.Modal.getInstance(modalElement);
myModal.hide();

After spending what felt like an eternity struggling with this, I realized that I was missing the bootstrap.Modal.getInstance method. It's funny how sometimes all it takes is reaching out for help to suddenly have a breakthrough!

Answer №3

A simple method to achieve this using Vanilla JavaScript when the close button is active:

document.querySelector('button.btn-close').click();

Answer №5

To conceal a modal declared in HTML without creating new instances, follow this approach:

bootstrap.Modal.getInstance(document.getElementById("foo")).hide();

If you encounter errors related to availability while working with the Vite builder, ensure that Bootstrap is properly included:

import * as bootstrap from 'bootstrap'
window.bootstrap = bootstrap;

Answer №6

For those struggling to understand why their modal.hide() isn't working with an eventListener(), here's the explanation:

If you have this code:

document.getElementById('add_tag').addEventListener('click', (e)=>{
    var modal = new bootstrap.Modal(document.getElementById("successModal"));
    modal.show();
});

document.getElementById('addButton').addEventListener('click', ()=>{
    var modal = new bootstrap.Modal(document.getElementById("successModal"));
    modal.hide();
});

It's important to note that in the first instance, using show() works fine because a new modal is defined and referenced by modal.show().

The problem arises when trying to close the modal upon clicking something. You can't create a new modal and expect it to close the old one.

To resolve this, move

var modal = new bootstrap.Modal(document.getElementById("successModal"));
outside of the eventListener function. This way, both functions can access var modal and utilize show() and hide() without issues.

var modal = new bootstrap.Modal(document.getElementById("successModal"));
document.getElementById('add_tag').addEventListener('click', (e)=>{
    modal.show();
});
document.getElementById('addButton').addEventListener('click', ()=>{
    modal.hide();
});

Answer №7

This approach was quite effective for me.

$('#nameModal').modal('close');

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

Plugin for jQuery that smoothly transitions colors between different classes

After searching through numerous jQuery color plugins, I have yet to discover one that allows for animating between CSS class declarations. For instance, creating a seamless transition from .class1 to .class2: .class1 { background-color: #000000 } .class ...

Adding an item to a collection using NgRx

I am working with a state that has a specific structure. It consists of a list of Workouts, and each Workout contains a list of exercises associated with it. I have two main objectives: To add new exercises to a particular workout from the existing list o ...

splitting the array elements in JavaScript

I'm having trouble with my code that is supposed to separate the array in customer and customerportals. let j = 0; let k = 0; let myVar = []; $.each(Object.customer, function(index, value) { $.each(value.portal.customerPortal, function(innerIn ...

Steps to make pop-up iframe function on the same page within a react nextjs application

My vanilla Html app has a pop-up feature that functions perfectly. When the button is clicked, the pop-up opens and everything works as expected. However, I am encountering an issue when trying to implement this same functionality in my React, NextJS app. ...

What is the best way to create a transparent sticky header that blends with the background while still maintaining visibility over images and text?

On my web page, the background features a radial gradient but the content extends beyond the viewport, causing the center of the gradient to not align with the center of the screen, producing the desired effect. However, I'm facing an issue with a sti ...

Create a search feature based on names utilizing Node Express in conjunction with SQL database

After deciding to create an API with a search feature using SQL queries in node express, this is how I structured my code: app.get('/search/:query', (req, res) => { pool.getConnection((err, connection) => { if(err) throw err ...

The jQuery prop("disabled") function is not operating as expected

Although I've seen this question answered multiple times, none of the suggested solutions seem to be working for my specific example. Hopefully, a fresh set of eyes can help me figure out what's going wrong. Even after adding alerts to confirm t ...

Adjusting the waterlevel model attribute to its standard value

In my Sails.js project, I am looking to reset a model attribute back to its original default value. By default value, I mean the value specified using defaultsTo in the model file. I have attempted methods such as: model.update({id:exampleId}, {myAttrib ...

Scrolling and hovering now triggers the fixed button to toggle class seamlessly

Currently, I am attempting to modify the class of a button on my website. The initial state of the button is wide, but as the user scrolls, it should shrink in size. When hovering over the shrunken button, it should expand back to its original width. Alt ...

Discover potential routes to nodes using JavaScript

I need assistance displaying all potential node paths in JavaScript: var object = {"metadata":{"record_count":5,"page_number":1,"records_per_page":5},"records":[{"name":"Kitchen","id":666,"parent_id":0,"children":null},{"name":"Jewellery","id":667,"pare ...

javascriptcode to execute before loading google maps

I am facing an issue with displaying markers on Google Maps. The problem arises when the array with latitude and longitude values is constructed through an Ajax request. Due to the map being loaded before the initialization of the array, I am unable to see ...

Executing JavaScript code does not execute CSS code

Having some trouble with my Javascript and CSS. The script is functioning well, but when I use the filtering function, the CSS stops working and only the filtered results are displayed on the HTML page. Looking for advice on how to fix the Javascript. & ...

Determine whether a JavaScript string exclusively consists of punctuation marks

In an if statement, I want to verify whether the given string contains any punctuation. If it does contain punctuation marks, I intend to display a pop-up alert message. if((/*regex presumably*/.test(rspace))==true||(/*regex presumably*/.test(sspace))==tr ...

In Express.js, what is the best way to redirect to a specific route after sending a response to the client side?

As a beginner learning Express.JS, I am facing an issue with redirecting routes. My goal is to display a message to the user saying "Your data has been registered successfully." and then redirect them back to the form page after a certain time period. Howe ...

What is the best way to transfer the array from my function and have it returned?

I've been struggling to successfully pass my array to an external function. Can anyone help me with this? You can find the code that I'm working on in jsbin: https://jsbin.com/kugesozawi/edit?js,console,output. The expected result should be passe ...

Creating a dynamic interaction between HTML forms and JavaScript using the onsubmit event handler

Having trouble getting my JavaScript file to fire when clicking the submit button on my simple HTML form. Can anyone provide some assistance? **UPDATED CODES Here is a snippet of my condensed HTML file: <html> <form name="form01" id="form01" ac ...

Angular JS failing to display error messages

I'm experiencing difficulties displaying login validation errors with the following code. After clicking on the Login button, it redirects to the next page without showing error messages as expected. Any suggestions? index.html:- <!DOCTYPE ht ...

The use of jQuery ajax requests is leading to a refresh of the page

I've encountered an issue with a button on my HTML page that is not associated with any form. <input type='button' id='submitter' value='add'/> There is a click handler attached to it: $('#submitter').c ...

Switch off any other currently open divs

I'm currently exploring a way to automatically close other div's when I expand one. Check out my code snippet below: $( document ).ready(function() { $( ".faq-question" ).click(function() { $(this).toggleClass('open'); $(this ...

What is the best way to trigger two separate JavaScript/jQuery functions on a single HTML control, specifically a text field, in response to

Here is the HTML code I have for a text field where functions are implemented: <input type="text" class="form-control" size="20" onblur="GetLocation();" id="zip_code" name="zip_code" value=""> <input type="text" class="form-control" size="20" r ...