Toggle A Caption in Fancybox 3

March 27, 2018

View Demo on CodePen View Project on GitHub

Since the release of Fancybox 3 and all of its new options, I started looking for a way to incorporate the caption of an image and toggle it.  The default effect of this JQuery lightbox plugin is to hide and show the caption (along with all of the UI) when the lightbox is hovered.  I have adjusted this slightly so there is a toggle button added to the options and it toggles the caption.

There are two sections to creating this effect, the Javascript and the CSS.

Adjusting the CSS

While I don’t recommend adjusting the CSS file you call when implementing Fancybox 3, you can easily add your own CSS lines to override the default styling.

I am adding a little padding, adjusting the transition property to accommodate the toggle-in, and placing it out of the viewport so the user can’t see it.  I am also declaring a property for the class I will add to the Fancybox caption when toggled.  This allows us to control the styling and transition when it is in toggled on and off.

I am also adjusting the width of the custom button I plan on creating so it is not fixed like the others.

Adding Javascript to modify Fancybox 3 and its settings

Thanks to the Fancybox 3 documentation, it is incredibly easy to modify how the plugin animates and controls your content.  Normally, Fancybox 3 will work out of the box by simply adding a data-fancybox  attribute to your HTML element, but in this case we need to go a little further to adjust the settings.

In this case, we will be doing two things –

  1. Declaring a custom button for Fancybox 3
  2. Adding a click event to the button which toggles a CSS class

So, how do we do that?

Well, first, we are going to create the button with this Javascript:

Now, we need to ensure that when Fancybox is called that it understands to use our new button.  Let’s call Fancybox and determine which buttons it should use:

Lastly, we need to add a click event on this button, so it knows what to do!

Here we are saying — if this button is ever clicked, see if the caption already has our toggled class, and if not — add it!

That’s it!  You now have a Fancybox 3 plugin that toggles the caption.

Hopefully with this example, you are able to see the flexibility and customization the developers at FancyApps provide to their already stellar plugin.  You could easily develop a custom user-experience that goes much further than a simple Lightbox effect.  Feel free to comment and send me examples!

 

Leave a Reply

Your email address will not be published. Required fields are marked *