How to integrate FancyBox 3 on Ghost

How to integrate FancyBox 3 on Ghost

If you want to add a lightbox effect to your images, FancyBox is a jQuery library that you can use to display images, videos and more, is customizable and easy to use.

The Download link is available in the FancyBox website and Github.

To install this library on Ghost we need to add the style and the javascript library, there are two ways to do it:

  1. Use Code Injection and put the style in the blog Header and the javascript in the Blog Footer.
  2. In the Ghost theme put the style in the head and the script at the end of the body tag on the default.hbs.
<link rel="stylesheet" type="text/css" href="jquery.fancybox.min.css">
<script src="jquery.fancybox.min.js"></script>

Once we add the library we can use it in two ways:

  • Using the img HTML tag.
  • Using Markdown and a wrapper with Javascript.

Using img HTML tag

In Ghost is possible to use the img HTML tag instead Markdown to display images, use the img HTML tag is also useful if we want to specify the image size.

So we can use the HTML syntax to show images with FancyBox:

<a href="/content/images/image.png" data-fancybox="images" data-caption="Image caption">
    <img src="/content/images/image.png" alt="Image caption" />


FancyBox Example 1

Using Markdown and Javascript

If you want to use the default way with Markdown instead of the img HTML tag, you can use Javascript and put a wrapper to all images in your blog.

The code bellow should be inside the javascript file, if you are using Casper the default Ghost theme, the javascript file is /content/themes/casper/assets/js/index.js, another alternative is to use the Code Injection and insert the code between the <script></script> tags.

function aTagWrap(elem, elemClass, exclude) {
    var imgs = $(elem);
    if (imgs.length > 0) {
        imgs.each(function () {
            var $this = $(this);
            var imgLink = $this.attr('src'),
                caption = $this.attr('alt');

            if (!$this.hasClass(exclude)) {
                var html = '<a href=\"' + imgLink + '\" class=\"' + elemClass + '\"' +
                    'data-fancybox=\"images\" data-caption=\"' + caption + '\"></a>';

We can apply FancyBox to all images or specific images using the aTagWrap function, with this syntax:

  • SELECTOR is a jQuery selector (select images).
  • LINK CLASS is the class that will be applied to the FancyBox link.
  • SKIP CLASS FancyBox will be not applied to the images with this class.


aTagWrap('.post-content img', 'fancy-box', 'no-fancy-box');

![FancyBox Example 2](/content/images/2017/04/fancy-box-example2.jpg)