Search code examples
javascriptjquerymagnific-popup

magnific popup: open by clicking on something other than the image


Client has requested that the image caption completely cover the thumbnail on hover, so I now need to be able to click the caption to open Magnific Popup instead of the <a>. So far I have been able to do:

JS/jQuery:

jQuery(".caption").on("click", function(event) {
  var items = [];
  jQuery(".item").each(function() {
    items.push( {
      src: jQuery(this).find("a").first().attr("href")
    } );
  });
  jQuery.magnificPopup.open({
    type: 'image',
    gallery: {
      enabled: true
    },
    items: items,
    image: {
      titleSrc: function(item) {
        console.log( item.el );
        // return item.el.clone();
      }
    }
  });
});

See the fiddle for an example, and the HTML and CSS (plus alternative JS that doesn't work either).

It's giving me two blockers:

  1. It's always the first image that pops up, instead of the image that one clicked on.
  2. That part about return item.el.clone(); is commented out because it's producing an "item.el is undefined" error (which doesn't seem to happen when magnificPopup is instantiated via jQuery('.caption').magnificPopup() as opposed to jQuery.magnificPopup.open()). However, I need the caption HTML to show up in the popup as well.

Any help would be appreciated. Thanks.


Solution

  • When you use an array of items you can pass the index of the first item you want to show. So I have used var index = jQuery(this).parent().index() to get the index of the current clicked item and then passed that variable in to the magnificPopup function.

    To get the caption in the popup I have added an extra property to the items object called titleSrc, which you can then retreive in the titleSrc option using item.data.titleSrc.

    https://jsfiddle.net/sjp7j1zx/4/

    jQuery(".caption a").on("click", function(event) {
      event.stopPropagation();
    });
    
    jQuery(".caption").on("click", function(event) {
      var items = [];
      jQuery(".item").each(function() {
        // Pass an extra titleSrc property to the item object so we can use it in the magnificPopup function
        items.push( {
          src: jQuery(this).find("a").first().attr("href"),
          titleSrc: jQuery(this).find('.caption').html()
        } );
      });
    
      // Get the index of the current selected item
      var index = jQuery(this).parent().index();
    
      jQuery.magnificPopup.open({
        type: 'image',
        gallery: {
          enabled: true
        },
        items: items,
        image: {
          titleSrc: function(item) {
           // get the titleSrc from the data property of the item object that we defined in the .each loop
           return item.data.titleSrc;
          }
        }
        // Pass the current items index here to define which item in the array to show first
      }, index);
    });