Magnific-Popup icon indicating copy to clipboard operation
Magnific-Popup copied to clipboard

Quick way to assign browser's back button to popup closing?

Open hardsubs opened this issue 9 years ago • 4 comments

There must be a solution already, did not find it here though. This will be useful for mobile devices, as users often touch back arrow to exit everything.

hardsubs avatar May 29 '16 19:05 hardsubs

I added a data-attribute to my gallery items like

<div class="gallery-item" data-pos="1">
...

then I looked up the data in the "change" callback and added a location hash. Works well also on mobile devices.

change: function() {
 var target = this.content,
       pos = target.data().pos;
window.location.hash = 'image-'+pos;                                        
 }

fietstouring avatar Oct 14 '16 14:10 fietstouring

I have implemented for now:

// back button closes magnific popup if popup is shown
if (window.history && window.history.pushState) 
{
    window.history.pushState('forward', null, window.location);
	
    $(window).on('popstate', function() {
		if( $('body').find('.mfp-wrap').is(':visible') ) {
			$('.mfp-close').click();
		}
    });
}

But it does not work after 3 - 4 openings and closes. I still don't know why.

q2apro avatar May 12 '21 08:05 q2apro

Solution:

  1. Add a callback in your magnific-popup code:
	// popup in iframe (or image etc.)
	$('.magnific-iframe').magnificPopup({
		type: 'iframe',
		mainClass: 'mfp-fade',
		preloader: false,
		fixedContentPos: false, 
		callbacks: {
			beforeOpen: function() {
				window.history.pushState('forward', null, window.location+'#iframe');
			},
			beforeClose: function() {
				if(window.location.hash) 
				{
					window.history.back();
				}
			},
		}
	});
  1. Have this code in your JS file:
// back button closes magnific popup if popup is shown
if (window.history && window.history.pushState) 
{
	// window.history.pushState('forward', null, window.location);
	
    $(window).on('popstate', function() 
	{
		if( $('body').find('.mfp-wrap').is(':visible') )
		{
			$('.mfp-close').click();
		}
	});
}

q2apro avatar May 12 '21 08:05 q2apro

q2apro

Hi, I add your first code at the end of jquery.magnific-popup.min.js and your second code to jquery.js. is not working for me, I did properly or I need to do something more?

celestedario avatar Dec 20 '21 15:12 celestedario