Magento 2 – JS Modal Popup Close Event

magento2modalpopup

require(
        [
            'jquery',
            'Magento_Ui/js/modal/modal'
        ],
        function(
            $,
            modal
        ) {
            var options = {
                type: 'popup',
                responsive: true,
                innerScroll: true,
                title: 'Title',
                buttons: [{
                    text: $.mage.__('Proceed'),
                    class: '',
                    click: function () {
                        /* some stuff */
                        this.closeModal();
                    }
                }]
            };
            var popup = modal(options,$('#popup-modal'));            
            $('#popup-modal').modal('openModal');
        }
    );

Popup works fine but I want to execute some code when the popup closes.

Thanks for the answers,

Popup can be closed by clicking x button or escape key.

But I don't think adding multiple events for click and keypress is a good idea.

Best Answer

You don't have to extend the modal.

You simply have to listen for the 'modalclosed' event on the DOM element on which the modal had been invoked. In fact the modal() function returns this element which makes the code trivial.

$('#popup-modal').on('modalclosed', function() { 
  /*insert code here*/ 
});
Related Topic