vincent15000's avatar

Bootstrap 5 problem with : new bootstrap.Modal()

Hello,

I use Bootstrap 5 CSS framework.

I have a modal window to create / edit a type.

When I click on the save button, I don't use the bootstrap attributes, I have to close the modal window using Javascript in order to be able not to close the window in case of a validation error.

I have written the code in the bootstrap documentation.

document.addEventListener('DOMContentLoaded', () => {
    document.addEventListener('closeModal', () => {
        var modal = new bootstrap.Modal('#typeForm');
        modal.hide();
    });
});

But I have this error.

Uncaught ReferenceError: bootstrap is not defined

I don't understand why bootstrap is not defined. I have this in my bootstrap.js file.

window._ = require('lodash');
import "bootstrap";
window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

Do you have any idea how to solve this issue ?

Thanks for your help.

Vincent

PS I'm French and I often see issue instead of problem or bug. What's the official word ? What's exactly an issue in English ?

0 likes
5 replies
martinbean's avatar
Level 80

@vincent15000 You’re trying to use window.bootstrap but you haven’t actually assigned it. Importing an NPM module doesn’t automatically add it to the window object.

Import the Bootstrap library and then actually assign it to the window object:

import * as bootstrap from 'bootstrap';

window.bootstrap = bootstrap;
3 likes
vincent15000's avatar

@martinbean That's a good idea ;) ... now effectively the new bootstrap.Modal() seems to work, but the modal.hide(); doesn't work. And I receive no error in the console.

vincent15000's avatar

@martinbean Hello ... well at least I have found the solution.

This does not work.

document.addEventListener('DOMContentLoaded', () => {
    document.addEventListener('closeModal', () => {
        var modal = new bootstrap.Modal('#typeForm');
        modal.hide();
    });
});

And this works.

document.addEventListener('DOMContentLoaded', () => {
    var modal = new bootstrap.Modal('#typeForm');
    document.addEventListener('closeModal', () => {
        modal.hide();
    });
});

I just had to put the modal variable outside the event listener.

1 like
aboozar_k's avatar

@martinbean

that's right. this two line insert after

import 'bootstrap';

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

Please or to participate in this conversation.