Events
Fancybox exposes custom events that can be hooked on to. To set event listeners, use the on option when setting up Fancybox, or you can use the on() API method.
Fancybox.bind("[data-fancybox]", {
on: {
close: () => {
console.log("Fancybox is closing!");
},
},
});Note that Fancybox is built around the Carousel component, so you need to listen to Carousel events if you want to listen, for example, to a slide change event, or to know when content is loaded into a carousel slide.
To make it easier to listen to Carousel events, they are available in Fancybox with the prefix carousel, for example:
Fancybox.bind("[data-fancybox]", {
on: {
"Carousel.change": (fancyboxRef, carouselRef) => {
console.log(`Carousel is changing to #${fancyboxRef.getSlide().index}`);
},
},
});Available Events
| Name | Description |
|---|---|
| * | Any event |
Carousel.* | Any Carousel event |
init | Initialization has started |
initPlugins | Plugins have been initialized |
initSlides | Slides have been initialized |
initLayout | Layout has been initialized |
initCarousel | Carousel has been initialized |
ready | Initialization has been completed |
keydown | A keyboard button is pressed |
shouldClose | Closing has begun and can be prevented |
close | Closing is ongoing |
destroy | Instance is detroyed |
Tips and Tricks
Any event
If you use * as the name of the event, you can listen to any event. This way you can quickly check what events are available, including events emitted by the Carousel and its plugins. Here is an example:
Fancybox.bind("[data-fancybox]", {
on: {
"*": (fancyboxRef, eventName) => {
console.log(`Fancybox eventName: ${eventName}`);
},
},
});Current slide
A fairly common need is to do something when a Fancybox starts or when a Carousel item changes. For example, you might want to get information from the current trigger element to update an element on the page. You can use Carousel.ready and Carousel.change events for this:
Fancybox.bind("[data-fancybox]", {
on: {
"Carousel.ready Carousel.change": () => {
const slide = Fancybox.getSlide();
console.log(`Current slide index: #${slide.index}`);
console.log(`Slide element:`);
console.log(slide.el);
console.log(`Corresponding trigger element:`);
console.log(slide.triggerEl);
},
},
});Content load
Use Carousel.contentReady event to detect when the content has been placed in the slide element and is ready to be displayed. The API method isCurrentSlide() can be used to determine whether content is loaded on the currently active slide or whether it is preloaded on another slide.
Fancybox.bind("[data-fancybox]", {
on: {
"Carousel.contentReady": (fancyboxRef, carouselRef, slide) => {
console.log(
`The content of the slide #${slide.index} is loaded; it ${
fancyboxRef.isCurrentSlide(slide) ? "is" : "is not"
} current slide`
);
},
},
});