August 24, 2018

Sreekanth B

Bind a function to Twitter Bootstrap Modal Close

the Twitter Bootstrap lib on a new project and I want for part of the page to refresh and retrieve the latest json data on modal close. I dont see this anywhere in the documentation can someone point it out to me or suggest a solution.

wo problems with using the documented methods

 $('#my-modal').bind('hide', function () {
   // do something ...
 });

I attach a "hide" class to the modal already so it does not display on page load so that would load twice

even if I remove the hide class and set the element id to display:none and add console.log("THE MODAL CLOSED"); to the function above when I hit close nothing happens.


Answers

Bootstrap 3

$('#myModal').on('hidden.bs.modal', function () {
    // do something…
})

Bootstrap 2.3.2

$('#myModal').on('hidden', function () {
    // do something…
})

Bootstrap 4

$('#my-modal').on('hidden.bs.modal', function () {
  window.alert('hidden event fired!');
});

Starting Bootstrap 3 (edit: still the same in Bootstrap 4) there are 2 instances in which you can fire up events, being:

1. When modal "hide" event starts

$('#myModal').on('hide.bs.modal', function () {
    console.log('Fired at start of hide event!');
});

2. When modal "hide" event finished

$('#myModal').on('hidden.bs.modal', function () {
    console.log('Fired when hide event has finished!');
});

Bootstrap provide events that you can hook into modal, like if you want to fire a event when the modal has finished being hidden from the user you can use hidden.bs.modal event like this

    /* hidden.bs.modal event example */
    $('#myModal').on('hidden.bs.modal', function () {
          window.alert('hidden event fired!');
    })

people using Bootstrap modals with React I've been using MutationObserver to detect changes in a modal's visibility and adjusting the state accordingly - this method could be applied to run any function when the modal is closed:

//react stuff
componentDidMount: function() {
    var self = this;
    $(function() {
        $("#example_modal").addClass('modal');
        //use MutationObserver to detect visibility change
        //reset state if closed
        if (MutationObserver) {
        var observer = new MutationObserver(function(mutations) {
            //use jQuery to detect if element is visible
            if (!$('#example_modal').is(':visible')) {
                //reset your state
                self.setState({
                    thingone: '',
                    thingtwo: ''
                });
            }
        });
        var target = document.querySelector('#example_modal');
            observer.observe(target, {
                attributes: true
          });
        }
    });
}


Subscribe to get more Posts :