Magnific-Popup
Magnific-Popup copied to clipboard
Use Magnific Popup with AJAX-loaded content
Hi,
I have some content that is loaded through AJAX. Magnific doesn't work with that content because the event listeners fire on page load, but the the AJAX-loaded content is not yet inserted in the page at that point.
The only workaround for this that I know of is to use inline javascript on the AJAX-loaded content. I tried to do something like:
<a class="test-popup-link" href="path-to-image.jpg" onclick="magnificPopup({type: 'image'}).magnificPopup('open');">Open popup</a>
But unfortunately it doesn't seem to work. I get ReferenceError: magnificPopup is not defined
, even though the magnific-popup.js file is included in the page.
Any help on how to get this to work would be appreciated. Thanks!
On document load initialize mp as normal:
jQuery(function () {
$(this).magnificPopup();
});
In your ajax call, trigger the binding of magnific popup after the ajax content is loaded:
$.ajax({
type: 'get',
url: '/get-ajax-content',
success: function (data) {
// Rebind modal events
$(this).magnificPopup();
}
});
In your magnificPopup jQuery function:
(function ($) {
$.fn.magnificPopup = function () {
$('[data-modal]').magnificPopup({
// options
});
return this;
};
})(jQuery);
use document
as main selector, but if you think it's too general, you can change it to any selector as long as it's not included inside AJAX dom element,
and then put your own selector (selector inside AJAX dom element) to delegate
options
$(document).magnificPopup({
delegate: '.your-class-selector',
});
It works for me, no need to re initialize
Thanks, it works.
If I use delegate then how do I get clicked element? is there any way of getting the click event?
use
document
as main selector, but if you think it's too general, you can change it to any selector as long as it's not included inside AJAX dom element,and then put your own selector (selector inside AJAX dom element) to
delegate
options$(document).magnificPopup({ delegate: '.your-class-selector', });
It works for me, no need to re initialize
thank you so much ! this works for me