Quick way to assign browser's back button to popup closing?
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.
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;
}
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.
Solution:
- 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();
}
},
}
});
- 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
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?