Magento – Close modal popup gracefully in magento2

addresscheckoutmagento2.2validation

I am using Magento modal popup for various functionalities in checkout.
I am working on an address validation module that fetches the corrected address from USPS API and displays the corrected address as an option in the popup. Now when the user selects the address and clicks on a button that changes the user address and closes the popup, I get the following error.

Uncaught TypeError: Cannot read property 'remove' of null
    at $.(anonymous function).(anonymous function)._destroyOverlay

This only happens when I close the popup and navigate to the next step at the same time.

But when I close the popup from the close button given by default on the popup, it does not give any error.

Best Answer

define(
[
    'jquery',
    'Magento_Ui/js/modal/modal'
],
function($) {
    "use strict";

    $.widget('mage.modalForm', {
        options: {
            modalForm: '#modal-lens-form',
            modalButton: '.open-modal-form'
        },
        _create: function() {
            this.options.modalOption = this._getModalOptions();
            this._bind();
            this._hide();
        },
        _getModalOptions: function() {
            /**
             * Modal options
             */
            var options = {
                type: 'popup',
                responsive: true,
                title: 'Select Product'
            };

            return options;
        },
        _bind: function(){
            var modalOption = this.options.modalOption;
            var modalForm = this.options.modalForm;

            $(document).on('click', this.options.modalButton,  function(){

                if ($('#product_addtocart_form').valid()) { //Open modal only if validation passes on base product form
                    //Initialize modal
                    $(modalForm).modal(modalOption);
                    //open modal
                    $(modalForm).trigger('openModal');
                }    
            });
        },
        _hide: function(){
            $(this.options.modalForm).hide();
        }
    }



    );

    return $.mage.modalForm;
}
);
Related Topic