Disappearing modal in Bootstrap 5 does not eliminate the backdrop

When using Bootstrap 5, I create my modal like this:

var myModal = new bootstrap.Modal(document.getElementById('scheduleMeetingModal'), {
    backdrop: 'static'
});
myModal.show();

Later on, when I want to hide the modal in another function, I use this code:

var myModalEl = document.getElementById('scheduleMeetingModal');
var myModal = bootstrap.Modal.getInstance(myModalEl);
myModal.hide();

However, the backdrop remains visible even after hiding the modal. I have tried various approaches without success, as mentioned in the following code snippet:

var myModalEl = document.getElementById('scheduleMeetingModal');
var myModal = bootstrap.Modal.getInstance(myModalEl);
myModal.hide();
myModal.modal({backdrop: false});

EDIT: Here is the HTML code for my modal:

<div class="modal" id="scheduleMeetingModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-dialog-centered modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header d-flex justify-content-between">
                <h5 class="modal-title" id="scheduleMeetingModalLabel"><?php echo lang('App.scheduleMeeting'); ?></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <?php echo form_open_multipart('schedule_meeting', 'id="schedule_meeting" class="needs-validation" novalidate=""'); ?>
                <div class="modal-body">
                    <div class="row form-row">
                        <div class="col-md-6">
                            <div class="mb-3 feature-info-content">
                                <label class="form-label" for="day_one"><?php echo lang('App.day'); ?> *</label>
                                <input class="form-control" type="date" id="day_one" required name="day_one">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3 feature-info-content">
                                <label class="form-label" for="time_one"><?php echo lang('App.startTime'); ?> *</label>
                                <input class="form-control" type="time" id="time_one" required name="time_one">
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="submit" id="schedule_meeting" class="btn btn-primary ms-5"><?php echo lang('App.submit'); ?></button>
                </div>
            </div>
        <?php echo form_close(); ?>
    </div>
</div>

Answer №1

After carefully evaluating the initial response, I came to the realization that the modal instance retrieval process was flawed. In line with the guidance provided in the Bootstrap 5 documentation, it is possible to both set and retrieve an existing instance of the modal object.

With this new insight, I made the necessary adjustments to my code and successfully resolved the issue:

var myModalEl = document.querySelector('#scheduleMeetingModal');
var myModal = bootstrap.Modal.getOrCreateInstance(myModalEl);
myModal.hide();

By implementing this revised code snippet, I achieved the desired outcome of hiding the backdrop without the need for any further modifications or the global declaration of the modal instance.

Answer №2

const meetingModalElement = document.querySelector('#meetingModal');
const meetingModal = bootstrap.Modal.getOrCreateInstance(meetingModalElement);
meetingModal.close();

Unfortunately, the initial solution did not work for me either. I found success by adding:

$('modal-backdrop').hide();

This removed the backdrop and resolved the issue.

Answer №3

After reviewing the code provided, I have identified and corrected the errors in the JavaScript portion. You can now run the updated code to ensure that it functions correctly.

var modal = new bootstrap.Modal(
  document.getElementById("scheduleMeetingModal")
);

function openModal() {
  modal.show();
}

function closeModal() {
  modal.hide();
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />


<button class="btn btn-primary" onclick="openModal()">Open Modal</button>
<!-- Modal -->


<div class="modal" id="scheduleMeetingModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header d-flex justify-content-between">
                <h5 class="modal-title" id="scheduleMeetingModalLabel"><?php echo lang('App.scheduleMeeting'); ?></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close" onclick="closeModal()"></button>
            </div>
            <?php echo form_open_multipart('schedule_meeting', 'id="schedule_meeting" class="needs-validation" novalidate=""'); ?>
                <div class="modal-body">
                    <div class="row form-row">
                        <div class="col-md-6">
                            <div class="mb-3 feature-info-content">
                                <label class="form-label" for="day_one">
                                    <?php echo lang('App.day'); ?> *</label>
                                <input class="form-control" type="date" id="day_one" required name="day_one"> </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3 feature-info-content">
                                <label class="form-label" for="time_one">
                                    <?php echo lang('App.startTime'); ?> *</label>
                                <input class="form-control" type="time" id="time_one" required name="time_one"> </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="submit" id="schedule_meeting" class="btn btn-primary ms-5">
                        <?php echo lang('App.submit'); ?>
                    </button>
                </div>
        </div>
        <?php echo form_close(); ?>
    </div>
</div>


<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ec9c839c9c899ec2869facddc2dddac2dc">[email protected]</a>/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>

Answer №4

When implementing Bootstrap V5, be mindful of the modal element provided in the documentation; ensure it does not include the "fade" class. Removing this class should allow the solution suggested by OP to function properly.

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

Effortlessly fill dropdown menus with data from JSON files

I've been using this jQuery code successfully, but I recently needed to add 3 more field columns to the JSON. My goal is to have the HTML select drop-downs dynamically change based on the data from the previous drop-down. Additionally, my current jQue ...

Is there a way to bring my popup closer to my button?

Check out my jsfiddle example here: https://jsfiddle.net/annahisenberg/ft10ersb/34/ Currently, I have the following code: <div id="more_options_popup" style={{ left: this.ref.current.offsetLeft - 140 + "px", top: this.ref.current.offsetTo ...

Utilizing Javascript to retrieve the current Controller and Action in Rails

Is it possible for JavaScript to determine the current controller and action in Rails? I had the idea of creating a hidden container to store the current controller and action, but I'm curious if there is a specific JavaScript function for this purpo ...

Issues with the execution of Typescript decorator method

Currently, I'm enrolled in the Mosh TypeScript course and came across a problem while working on the code. I noticed that the code worked perfectly in Mosh's video tutorial but when I tried it on my own PC and in an online playground, it didn&apo ...

The transition from Vuetify3's VSimpleTable to VTable is ineffective and unsuccessful

The v-simple-table component has been renamed to v-table Old code that was using v-simple-table may not work correctly after the renaming. It is recommended to use v-data-table with the same data, as it works correctly. https://i.sstatic.net/3GVdYMWl.png ...

Finding the amount of memory that can be used in a WebView

I'm currently developing an application that features a WebView running JavaScript code. This particular JavaScript code tends to be memory-intensive and can sometimes exceed the allotted memory, leading to crashes in the WebView's Chromium proce ...

Using a dojo widget within a react component: A beginner's guide

Has anyone found a way to integrate components/widgets from another library into a react component successfully? For example: export default function App() { const [count, setCount] = useState(0); return ( <button onClick={() => setCount(count + ...

Configure environment variables for either grunt or grunt-exec

Attempting to utilize grunt-exec for executing a javascript test runner while passing in a deployed link variable. This is being done by initializing an environment variable grunt.option('link') with the help of exec:setLink. Within my test_runn ...

Discovering the position of an element within an array and leveraging that position to retrieve a corresponding value from a separate array

const STATE = ["TEXAS","CALIFORNIA","FLORIDA","NEW YORK"] const STATE_CODE = ["TX","CA","FL","NY"] With two arrays provided, the first array is displayed in a dropdown menu. The challenge is to retrieve the corresponding state code from the second array ...

Tips for segmenting text into pages according to the dimensions of the viewport and the font style

Here's a puzzle for you. I have a horizontal slider that loads pages via Ajax, with pre-loading features to maintain smooth performance. Similar to Facebook Billboarding but with a slight twist. By determining the viewport size, I calculate boxSizeX a ...

confirmation box for deleting a row in a grid view

I am looking to enhance the delete confirmation box on my Gridview delete function. Currently, I am using a basic Internet Explorer box for confirmation but I want to display a more stylish confirmation box. Here is the JavaScript code snippet within my gr ...

The 'string' Type in Typescript cannot be assigned to the specified type

Within the fruit.ts file, I've defined a custom type called Fruit which includes options like "Orange", "Apple", and "Banana" export type Fruit = "Orange" | "Apple" | "Banana" Now, in another TypeScript file, I am importing fruit.ts and trying to as ...

Validating dates in TypeScript

Currently, I am studying date handling and have an object that contains both a start and end date. For example: Startdate = "2019-12-05" and Enddate = "2020-05-20" My goal is to establish a condition that first verifies the dates are not empty. After tha ...

Using an Angular route to trigger the resolution of data from a service

I'm having trouble figuring out how to implement Angular route resolve. The documentation does not provide much help for more complex aspects of the javascript framework like this. Here is the service I am using: app.service("AuthService", ["$http", ...

Display the number of items that have been filtered as soon as the Mixitup page loads

Currently, I am utilizing MixItUp 3 for sorting and filtering items, with the goal of displaying the count of items within each filter category upon the initial page load. Despite attempting a solution found on SO (mixitup counting visible items on initial ...

What is the best way to integrate JQuery URL in Joomla components?

Can anyone show me how to load a jquery URL in Joomla (Component)? I have a button that, when clicked, will reload the page and use the GET method to display a value from a variable. JavaScript: jQuery("#btnclickme").click(function(){ jQuery("#divpro").l ...

What is the solution for the error message "TypeError: app.use() is seeking a middleware function"?

I am a beginner in Node.js and have encountered an issue in my passport.js or signupLogin.js file with the error message, app.use() requires a middleware function that I am struggling to resolve. I suspect it may be related to the signupLogin route, as th ...

Feeling grateful: Enable scroll functionality for a log widget

I am currently utilizing the Blessed library to create a dashboard within the terminal. My issue lies in making the log widget scrollable. Despite implementing the code below, I am unable to scroll using my mouse wheel or by dragging the scrollbar: var l ...

ajax - unable to fetch information from the same domain

UPDATE: The solution provided by Cavid Kərimov indeed works. By setting the form as shown below, it also resolves the issue. <form onsubmit="return false;"></form> I am attempting to fetch a simple text string from a PHP file using jQuery an ...

I am curious about why I am unable to utilize inline functions in component props. Could you please provide a detailed explanation and perhaps give an example to illustrate? Furthermore, what is

Please take note: The component prop accepts a component, not a render function. Do not pass an inline function (e.g. component={() => }), as this will cause your component to unmount and remount, losing all state when the parent component re-renders. F ...