Search code examples
javascriptjquerymagnific-popup

Add magnificPopup to dynamic created element


I worked with below code it will pop up the content I want

function init_magnificPopup()
{
    $('.popup-with-zoom-anim').magnificPopup({

        type: 'inline',

        fixedContentPos: false,
        fixedBgPos: true,

        overflowY: 'auto',

        closeBtnInside: true,
        preloader: false,

        midClick: true,
        removalDelay: 300,
        mainClass: 'my-mfp-zoom-in'
    });
}

$(document).ready(function() {
    init_magnificPopup();
});

HTML

<a class="btn btn-primary popup-with-zoom-anim" href="#dialog">dialog popup</a> 

<div id="dialog" class="zoom-anim-dialog mfp-hide">
popup content
</div>

Now how can I work with below dynamically created tag with class .popup-with-zoom-anim?

var content_string +=  '<a class="popup-with-zoom-anim" href="#dialog">dynamic dialog popup</a>';
$( "body" ).html(content_string);

Solution

  • I find the answer which using .on() method and chaining .magnificPopup('open'); to the end

    $("body").on('click', '.popup-with-zoom-anim', function(){ 
    
         $(this).magnificPopup({
    
                    type: 'inline',
    
                    fixedContentPos: false,
                    fixedBgPos: true,
    
                    overflowY: 'auto',
    
                    closeBtnInside: true,
                    preloader: false,
    
                    midClick: true,
                    removalDelay: 300,
                    mainClass: 'my-mfp-zoom-in'
                }).magnificPopup('open');
    
    });