Events
Listen to zoom events to respond when images open, close, or change. Each event is a CustomEvent dispatched on the original image element.
Event names
| Event | When it fires |
|---|---|
open | Opening starts. |
opened | The opening animation completes. |
close | Closing starts. |
closed | The closing animation completes. |
detach | An image is detached. |
update | Options are updated, on each attached image. |
If you close an image while it is opening, the open() promise resolves as part of cancellation. Use opened to observe a completed opening.
Listen to events
Pass an unprefixed event name to on():
js
import mediumZoom from 'medium-zoom'
const zoom = mediumZoom('[data-zoomable]')
zoom.on('opened', event => {
console.log('Image opened:', event.target)
})event.target is the original image. event.detail.zoom is the zoom instance.
The optional third argument accepts the same options as addEventListener(). For example, run a listener once per image:
js
zoom.on('closed', () => console.log('Image closed'), { once: true })Remove a listener
Pass the same function and capture setting to off():
js
const onOpened = () => console.log('Image opened')
zoom.on('opened', onOpened)
zoom.off('opened', onOpened)Native event listeners
To listen on an image directly, prefix the event name with medium-zoom::
js
const image = document.getElementById('cover')
image?.addEventListener('medium-zoom:opened', event => {
console.log('Image opened:', event.target)
})Use the unprefixed names with on() and off(), and the prefixed names with native event listeners.