img-previewer

View images the way iOS Photos does: a photo grows from its spot to the center of the screen and shrinks back when closed. Every animation runs on CSS transforms, so it stays smooth.

  • ≈ 5 KB JS gzipped
  • 0 dependencies
  • Pinch to zoom and keyboard shortcuts
npm i img-previewer

Controls

Once a photo is open you can use these. On touch screens, pinch to zoom.

  • ZoomMouse wheel or + -
  • PanDrag after zooming in
  • Previous / next← →
  • CloseEsc or click the backdrop
  • Rotate, zoom and resetToolbar, top right

Install

npm i img-previewer
# or
pnpm add img-previewer

Or load it from a CDN:

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/img-previewer/dist/index.css">
<script src="https://cdn.jsdelivr.net/npm/img-previewer/dist/img-previewer.min.js"></script>

Usage

Pass a CSS selector. Every <img> inside it opens on click, with no changes to your existing HTML.

import ImgPreviewer from 'img-previewer'
import 'img-previewer/dist/index.css'

const previewer = new ImgPreviewer('#app', {
  fillRatio: 0.8,
  onShow({ index, img }) {},
  onHidden({ index, img }) {}
})

Adding images later? Call previewer.update() after they render.

Options

NameDescriptionDefault
fillRatioHow much of the viewport the image fills0.8
dataUrlKeyAttribute that holds the full-size image URLsrc
triggerEventEvent that opens the viewer, click or dblclickclick
imageZoomZoom: min, max, step1 / 5 / 0.1
styleStyle: modalOpacity, headerOpacity, zIndex0.6 / 0 / 99
i18nToolbar tooltip text. Chinese or English by browser languageAuto
bubblingLevelHow many parent levels to check for CSS hiding0
hideOriginalHide the original image on the page while previewingtrue
durationOpen and close animation duration in ms, switching and zooming scale with it400
onBeforeShowCalled before opening, return false to cancel—
onShowCalled when the viewer starts opening—
onShownCalled after the open animation—
onChangeCalled when switching images, also gets prevIndex—
onBeforeHideCalled before closing, return false to cancel—
onHideCalled when the viewer starts closing (alias onClose)—
onHiddenCalled after the close animation—

Lifecycle hooks receive { index, img }, where img is the original image on the page.

Methods

MethodDescription
show(index)Open the image at an index
next() / prev()Go to the next / previous image
hide()Close the viewer
update()Re-collect images under the selector
getTotalIndex()Index of the last image
destroy()Remove listeners and DOM created by the instance