How to open a modal with Fancybox3

Posted by

Fancybox3 offers an easy solution for modal implementation on your website. It is simple, but sometimes documentation can spin your head. Let me show you the demonstration, and explain important parts of the API.

$.fancybox.open(items, opts, index);

How to open modal with HTML elements from the same page

Let’s say you have the modal content ready on the same page. You can create a modal instance with it. Documentation refers to this as inline modal since it will inject HTML elements inside a modal.

<div data-fp_modal="modalContent" style="display: none;">
  <!-- modal content -->
</div>

As you can see, there is a data property set on the HTML element. That way, you can retrieve that modal content by using document.querySelector. After retrieving that content, you pass it into the $.fancybox.open method and create an instance.

function openModal() {
  var modalContent = document.querySelector('[data-fp_modal="modalContent"]');
  $.fancybox.open(modalContent);
}

How do you set modal options?

You can set options for your modal. For example, “smallBtn: false” removes the small close button on the top right corner of modal. You can modify button templates in Fancybox3 by setting your own HTML tags with styles to btnTpl property. Furthermore, you can set up a callback function for after content is done loading and animating. Please check the documentation for more if you need more options.

var modalConfig = {
    smallBtn: false,
    btnTpl: {
        close: '...',
        download: '...',
    },
    afterShow: function(instance, current) {
        //...
    },
    //more options in the official documentation
}

$.fancybox.open(modalContent, modalConfig);

How to open modal by index

In the earlier example, we only set one modal content. However, there is also a case that there are a multiple items registered for a modal instance. In that case, you can select a particular item to be shown on modal by index.

var modalItems = [..., ..., ...];

$.fancybox.open(modalItems, { index: 1});

How to display an iframed page on modal

You can also display content from another page by using an iframe option. There are a couple of options for configuring how an iframe page should be loaded and appear on modal.

var modalConfig = {
  src: 'https://xxxxxx',
  type: 'iframe',
  opts: {
    smallBtn: false,
    iframe: {
      preload: false,
      css: {
        width: '300px',
        height: '200px'
      }
    }
  }
}
$.fancybox.open(modalConfig);

Codepen Examples

All the options here are demonstrated on my CodePen sandbox.

Thanks for reading.

Hope you enjoyed the article. If you have any question or opinion to share, feel free to write some comments.

Facebook Comments