How to close all active bootstrap modals on session timeout?

JavascriptJqueryTwitter BootstrapModal Dialog

Javascript Problem Overview


I need to make a call when the user is idle and passes the session time out that will close all Bootstrap modals. The modals being active are dependent on what the user is doing at the time so I would like to do something that's is all encompassing.

I tried:

$('.modal').modal('toggle');

When the time out occurs but my modals are still there.

Javascript Solutions


Solution 1 - Javascript

Use the following code:

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

Also if you would like to do something if the modal is hidden then you can do this:

$('.modal').on('hidden', function () {
  // write your code
});

Solution 2 - Javascript

The correct answer is missing something vital.

$('.modal').modal('hide') // closes all active pop ups.
$('.modal-backdrop').remove() // removes the grey overlay.

The second line is vital if you want the users to use the page as normal.

Solution 3 - Javascript

Try this way : $('.modal.in:visible').modal('hide');

Solution 4 - Javascript

This is how i got it working in my project without using any factory or additional code.

//hide any open bootstrap modals
  angular.element('.inmodal').hide();

I have a timeout function that emits logout as $rootScope.$emit('logout'); and the listener in my service is as follows:

$rootScope.$on('logout', function () {                    
                    //hide any open bootstrap modals
                    angular.element('.inmodal').hide();

                    //do something else here  

                });

If you want to hide any other modals such as angular material dialog ($mdDialog) & sweet alert dialog's use angular.element('.modal-dialog').hide(); & angular.element('.sweet-alert').hide();

I don't know if this is the right approach , but it works for me.

Solution 5 - Javascript

Using vanilla JS you can do the following

// import all your dependencies
import * as bootstrap from "bootstrap"

// close all modals but the one you want to open
const $modals =  document.querySelectorAll('.modal')
$modals.forEach(modal => {
  let currentModal = bootstrap.Modal.getInstance(modal)
  if (currentModal) currentModal.hide()
})

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionjeff wernerView Question on Stackoverflow
Solution 1 - JavascriptS. RaselView Answer on Stackoverflow
Solution 2 - JavascriptTom McDonoughView Answer on Stackoverflow
Solution 3 - JavascriptneTurmericView Answer on Stackoverflow
Solution 4 - JavascripthakunaView Answer on Stackoverflow
Solution 5 - Javascriptro_puenteView Answer on Stackoverflow