bootstrap: Can't close a Modal using JS

BS5-modal-hide-issue

As you can see, the backdrop is still there, after the modal gets closed

I could remove the backdrop myself document.querySelector('.modal-backdrop')?.remove() but that feels quite hacky, this internal part should be part of bootstrap API

About this issue

  • Original URL
  • State: open
  • Created 3 years ago
  • Reactions: 3
  • Comments: 20 (6 by maintainers)

Most upvoted comments

So do you guys want the hide method to work synchronously? 😟 Since the code that you wrote is fine IMO @alpadev

const modal = bootstrap.Modal.getInstance(modalEl);
modal.hide();
modalEl.addEventListener('hidden.bs.modal', () => {
  modal.dispose();
}, { once:true });

/CC @GeoSot

modal object should be initialized out of the click event, in this way it worked for me.

        const modalEle: HTMLElement = document.querySelector('#js-modal');
        const modal = new Modal(modalEle, {});

        document.querySelector('.close-button').addEventListener('click', (evt: Event) => {
            if (modalEle){
                modal.hide();
            }
        });

@caub glad if that works for you.

I’d prefer to leave this open tho, so that we can track this and maybe at some point come up with an easier solution. Or maybe we should open a new feature issue for this. 🤔

/CC @GeoSot @rohit2sharma95

Thanks for reporting this problem. You’re indeed correct with your expectation that this should be handled by our code.

As a workaround until it’s fixed you may want to use:

const closeWithJS = document.getElementById('closeWithJS');
const openWithJS = document.getElementById('openWithJS');
const modalEl = document.getElementById('exampleModal');

closeWithJS.onclick = () => {
  const modal = bootstrap.Modal.getInstance(modalEl);
  modal.hide();
  modalEl.addEventListener('hidden.bs.modal', () => {
    modal.dispose();
  }, {once:true});
};

openWithJS.onclick = () => {
  const modal = new bootstrap.Modal(modalEl);
  modal.show();
};

cc @GeoSot