magnific-popup

how to make browser back close magnific-popup


I have the popup working but sometimes a user clicks the back button on their browser to close the popup.

How can I make the browser back button close a 'magnific-popup' that is already open?

Thanks


Solution

  • After some digging found history.js and then the following

    var magnificPopup = null;
    jQuery(document).ready(function ($) {
        var $img = $(".img-link");
        if ($img.length) {
            $img.magnificPopup({
                type: 'image',
                preloader: true,
                closeOnContentClick: true,
                enableEscapeKey: false,
                showCloseBtn: true,
                removalDelay: 100,
                mainClass: 'mfp-fade',
                tClose: '',
                callbacks: {
                    open: function () {
                        History.Adapter.bind(window, 'statechange', closePopup);
                        History.pushState({ url: document.location.href }, document.title, "?large");
                        $(window).on('resize', closePopup);
                        magnificPopup = this;
                    },
                    close: function () {
                        $(window).unbind('statechange', closePopup)
                            .off('resize', closePopup);
                        var State = History.getState();
                        History.replaceState(null, document.title, State.data["url"]);
                        magnificPopup = null;
                    }
                }
            });
        }
    });
    
    function closePopup () {
        if (magnificPopup != null)
            magnificPopup.close();
    }