Search code examples
javascriptjquerymagnific-popup

Accessing attributes from Magnific Popup's calling button on Popup load


I have a page with several buttons that all open the same modal using Magnific Popup. However I need to customize the popup for each button according to the calling button's data- attributes.

So I need a way to call a function when the popup pops :-) and have access to the calling button.

The Magnific popup initialization is part of the FE's js file, and I'm working in the module's js file. So I'm trying to minimize changes to the FE's js!

Is this possible? How can I achieve this?


Solution

  • CHECK UPDATE BELOW:

    This is what I did:

    • Did not touch the FE's js which initialized any .my-modal class
    • I edited these button's classes from .my-modal into .my-custom-modal (for example)
    • Initialized magnificpopup on .my-custom-modal and added the following to trigger an event before opening the modal:

      $('.my-custom-modal').magnificPopup({
          type: 'inline',
          midClick: true
      }).on('mfpBeforeOpen', function () {
          // 'this' is the current button that triggered the modal
          console.log(this);
      });
      

    UPDATE The above works but the 'this' var wasn't returning the actual button but seems like the first button in the page. The below should work correctly:

    $('.my-custom-modal').magnificPopup({
    type: 'inline',
    midClick: true,
    callbacks: {
                open: function () {
                    var mp = $.magnificPopup.instance,
                        btn = $(mp.currItem.el[0]);
    
                    //btn is the actual button being clicked
                    console.log(btn);
                }
              }
    });