3

I want to use magnific popup on dynamically generated content. I have link generated via javascript and a want to use "iframe" magnific popup with this link.

HTML:

<div id="content">
  <a href="https://www.google.com/" class="mp">link</a>
</div>

JS:

$(function(){
    $('.mp').magnificPopup({
          type: 'iframe',
          closeOnContentClick: false,
          closeBtnInside: true,
          removalDelay: 300,
          mainClass: 'mfp-with-zoom mfp-img-mobile my-mfp-slide-bottom'
    });

    var a = $("a").clone();
    a.text('generated');
    a.appendTo('#content');

});

live example : jsfiddle

With classic static link everything works well but on generated link it doesn't work. Is there some "refresh" function which will register generated link to magnific popup scope?

I tried to construct new magnific instance after generating the link and it works, but is there some cleaner solution?

Thanks for any response.

mychalvlcek
  • 3,956
  • 1
  • 19
  • 34
  • 1
    Why does it happen? Well, JQuery uses the DOM to make its binds, so your code is expecting that '.mp' exists. You need to bind it someway in something that always is around, maybe the body. I don't know how to do it in JS, but it may be a start for you to research, maybe it's called "late bind" (basically put the body as a observer). – MVCDS Oct 06 '14 at 20:30
  • 1
    [Maybe an answer](http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – MVCDS Oct 06 '14 at 20:32

1 Answers1

6

Thanks to @MVCDS i figured it out, theres option for this.

$('body').magnificPopup({
      delegate: 'a.mp',
      type: 'iframe',
      closeOnContentClick: false,
      closeBtnInside: true,
      removalDelay: 300,
      mainClass: 'mfp-with-zoom mfp-img-mobile my-mfp-slide-bottom'
});
mychalvlcek
  • 3,956
  • 1
  • 19
  • 34