user2233208
user2233208

Reputation:

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

Upvotes: 3

Views: 2912

Answers (3)

Alexcool
Alexcool

Reputation: 63

I'm using this solution:

callbacks: {   
        open: function() {
          location.href = location.href.split('#')[0] + "#gal";
        }
        ,close: function() {
          if (location.hash) history.go(-1);
        }
      }

And this code:

$(window).on('hashchange',function() {

       if(location.href.indexOf("#gal")<0) {

         $.magnificPopup.close(); 
       }
  });

So, on gallery open I add #gal hash. When user closes I virtually click back button to remove it. If user clicks back button - everything works fine olso.

This solution does not break back button behavior and does no require any additional plugins.

Comments are welcome.

Upvotes: 3

Overload119
Overload119

Reputation: 5396

Just to add to your answer, these are the meaningful lines that I got to work for me.

      callbacks:
        open: ->
          History.pushState({ url: document.location.href }, null, "?dialogOpen")
          History.Adapter.bind(window, 'statechange', attemptToCloseDialog)
        close: ->
          $(window).unbind('statechange', attemptToCloseDialog)
          History.replaceState(null, null, History.getState().data['url'])

With attempt being:

attemptToCloseDialog = ->
  $.magnificPopup.close() if $.magnificPopup.instance

Upvotes: 0

user2233208
user2233208

Reputation:

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();
}

Upvotes: 3

Related Questions