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

Use Magnific Popup with AJAX-loaded content

Open BorislavZlatanov opened this issue 7 years ago • 5 comments

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!

BorislavZlatanov avatar May 16 '17 10:05 BorislavZlatanov

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

ragoutje avatar Jun 21 '17 12:06 ragoutje

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

agussuroyo avatar May 07 '20 07:05 agussuroyo

Thanks, it works.

waleed-mubarik avatar Sep 29 '20 09:09 waleed-mubarik

If I use delegate then how do I get clicked element? is there any way of getting the click event?

prionkor avatar Oct 15 '20 14:10 prionkor

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

HmHasan22 avatar Jun 28 '22 12:06 HmHasan22