Search code examples
javascriptjquerymagnific-popup

Magnific Popup: How to modify showCloseBtn and closeOnBgClick while open?


Is there a way to edit an open instance of a magnific popup? In one state I want the popup to be closable, and in another state I want to block user from closing. It seems these options are only available for intilialisation:

$('.target-div').magnificPopup({
    delegate: 'a',
    type: "inline",
    closeOnBgClick: true,
    showCloseBtn: true,
    gallery: {
        enabled: false
}})

Then, while the popup is open, I want to block accidental closing and take away the X button.

$('.target-div').magnificPopup({
    delegate: 'a',
    type: "inline",
    closeOnBgClick: false,
    showCloseBtn: false,
    gallery: {
        enabled: false
}})

Solution

  • MagnificPopup stores a single instance in the jQuery var ($.magnificPopup), which controls the popup's behavior in the DOM. It's actually really easy to update the background click behavior by changing a single setting.

    $.magnificPopup.instance.st.closeOnBgClick = false
    

    Internally, MFP uses $.detach() and $.append() to control the presence of the close button. To remove it, we can duplicate the way it works in _close() by calling:

    $.magnificPopup.instance.currTemplate.closeBtn.detach()
    

    Re-adding it is a bit more difficult because the library uses a private function called _getCloseBtn() to generate the element. Fortunately we can just re-append it from the same place we removed it.

    $.magnificPopup.instance.content.append($.magnificPopup.instance.currTemplate.closeBtn)
    

    Source: https://github.com/dimsemenov/Magnific-Popup/blob/c8f6b8549ebff2306c5f1179c9d112308185fe2c/dist/jquery.magnific-popup.js

    Demo page used for testing: https://dimsemenov.com/plugins/magnific-popup/