πŸ”ŽπŸ–Ό A JavaScript library for zooming images like Medium
Clone or download
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
.github docs(github): Update default sandbox link Aug 31, 2018
cypress test(cypress): Increase image snapshot threshold Aug 28, 2018
docs docs(migrations): Remove migration guide in favor of releases Aug 28, 2018
examples chore(deps): upgrade dependencies (#80) Nov 4, 2018
src docs: fix typos in comments Nov 7, 2018
stories feat(api): Rename getZoomedTarget() to getZoomedImage() Aug 28, 2018
website chore(deps): upgrade dependencies (#80) Nov 4, 2018
.babelrc build(rollup): Update Rollup config Aug 28, 2018
.editorconfig Init Jul 26, 2016
.eslintignore build(test): Update Jest scripts Aug 22, 2018
.eslintrc.js chore(eslint): Update ESLint config Aug 28, 2018
.gitignore test(cypress): Migrate end-to-end tests to Cypress Aug 22, 2018
.nvmrc build(node): Upgrade Node version Sep 5, 2018
.prettierrc style: Format with trailing commas Jul 28, 2018
.release-it.json build(release): Don't require clean working dir Aug 27, 2018
.travis.yml ci(travis): Rely on .nvmrc Aug 28, 2018
CONTRIBUTING.md docs(contributing): Add contributing guide Aug 25, 2018
LICENSE feat: Add website (#63) Jul 29, 2018
README.md docs(readme): Rephrase `detach()` method Sep 5, 2018
cypress.json build(cypress): Ignore fixtures folder Aug 22, 2018
jest.config.js test(module): Check that module is exported Aug 22, 2018
logo.svg Add logo Sep 20, 2017
netlify.toml feat: Add website (#63) Jul 29, 2018
package.json chore(deps): upgrade dependencies (#80) Nov 4, 2018
rollup.config.js build(rollup): Update Rollup config Aug 28, 2018
yarn.lock chore(deps): upgrade dependencies (#80) Nov 4, 2018

README.md

Demo

medium-zoom

A JavaScript library for zooming images like Medium

version MIT license downloads
gzip size no dependencies travis

Medium Zoom Demo

πŸ”¬ Playground ・ πŸ”Ž Demo ・ πŸ“š Storybook

Contents

Features

  • πŸ“± Responsive β€” scale on mobile and desktop
  • πŸš€ Performant and lightweight β€” should be able to reach 60 fps
  • ⚑️ High definition support β€” load the HD version of your image on zoom
  • πŸ”Ž Flexibility β€” apply the zoom to a selection of images
  • πŸ–± Mouse, keyboard and gesture friendly β€” click anywhere, press a key or scroll away to close the zoom
  • πŸŽ‚ Event handling β€” trigger events when the zoom enters a new state
  • πŸ“¦ Customization β€” set your own margin, background and scroll offset
  • πŸ”§ Pluggable β€” add your own features to the zoom
  • πŸ’Ž Custom templates β€” extend the default look to match the UI of your app

Installation

The module is available on the npm registry.

npm install medium-zoom
# or
yarn add medium-zoom
Download
CDN

Usage

Try it out in the browser

Import the library as a module:

import mediumZoom from 'medium-zoom'

Or import the library with a script tag:

<script src="node_modules/medium-zoom/dist/medium-zoom.min.js"></script>

That's it! You don't need to import any CSS styles.

mediumZoom('[data-zoomable]')

API

mediumZoom(selector?: string|Element|NodeList|Array, options?: object) => Zoom

Selectors

The selector allows attaching images to the zoom. It can be of the following types:

// CSS selector
mediumZoom('[data-zoomable]')

// Element
mediumZoom(document.querySelector('#cover'))

// NodeList
mediumZoom(document.querySelectorAll('[data-zoomable]'))

// Array
const images = [
  document.querySelector('#cover'),
  ...document.querySelectorAll('[data-zoomable]'),
]

mediumZoom(images)

Options

The options enable the customization of the zoom. They are defined as an object with the following properties:

Property Type Default Description
margin number 0 The space outside the zoomed image
background string "#fff" The background of the overlay
scrollOffset number 40 The number of pixels to scroll to close the zoom
container string|Element|object null The viewport to render the zoom in
Read more β†’
template string|Element null The template element to display on zoom
Read more β†’
mediumZoom('[data-zoomable]', {
  margin: 24,
  background: '#BADA55',
  scrollOffset: 0,
  container: '#zoom-container',
  template: '#zoom-template',
})

Methods

open({ target?: Element }) => Promise<Zoom>

Opens the zoom and returns a promise resolving with the zoom.

const zoom = mediumZoom('[data-zoomable]')

zoom.open()

Emits an event open on animation start and opened when completed.

close() => Promise<Zoom>

Closes the zoom and returns a promise resolving with the zoom.

const zoom = mediumZoom('[data-zoomable]')

zoom.close()

Emits an event close on animation start and closed when completed.

toggle({ target?: Element }) => Promise<Zoom>

Opens the zoom when closed / dismisses the zoom when opened, and returns a promise resolving with the zoom.

const zoom = mediumZoom('[data-zoomable]')

zoom.toggle()

attach(...selectors: string[]|Element[]|NodeList[]|Array[]) => Zoom

Attaches the images to the zoom and returns the zoom.

const zoom = mediumZoom()

zoom.attach('#image-1', '#image-2')
zoom.attach(
  document.querySelector('#image-3'),
  document.querySelectorAll('[data-zoomable]')
)

detach(...selectors: string[]|Element[]|NodeList[]|Array[]) => Zoom

Releases the images from the zoom and returns the zoom.

const zoom = mediumZoom('[data-zoomable]')

zoom.detach('#image-1', document.querySelector('#image-2')) // detach two images
zoom.detach() // detach all images

Emits an event detach on the image.

update(options: object) => Zoom

Updates the options and returns the zoom.

const zoom = mediumZoom('[data-zoomable]')

zoom.update({ background: '#BADA55' })

Emits an event update on each image of the zoom.

clone(options?: object) => Zoom

Clones the zoom with provided options merged with the current ones and returns the zoom.

const zoom = mediumZoom('[data-zoomable]', { background: '#BADA55' })

const clonedZoom = zoom.clone({ margin: 48 })

clonedZoom.getOptions() // => { background: '#BADA55', margin: 48, ... }

on(type: string, listener: Function, options?: object) => Zoom

Registers the listener on each target of the zoom.

The same options as addEventListener are used.

const zoom = mediumZoom('[data-zoomable]')

zoom.on('closed', event => {
  // the image has been closed
})

zoom.on(
  'open',
  event => {
    // the image has been opened (tracked only once)
  },
  { once: true }
)

The zoom object is accessible in event.detail.zoom.

off(type: string, listener: Function, options?: object) => Zoom

Removes the previously registered listener on each target of the zoom.

The same options as removeEventListener are used.

const zoom = mediumZoom('[data-zoomable]')

function listener(event) {
  // ...
}

zoom.on('open', listener)
// ...
zoom.off('open', listener)

The zoom object is accessible in event.detail.zoom.

getOptions() => object

Returns the zoom options as an object.

const zoom = mediumZoom({ background: '#BADA55' })

zoom.getOptions() // => { background: '#BADA55', ... }

getImages() => Element[]

Returns the images attached to the zoom as an array of Elements.

const zoom = mediumZoom('[data-zoomable]')

zoom.getImages() // => [Element, Element]

getZoomedImage() => Element

Returns the current zoomed image as an Element or null if none.

const zoom = mediumZoom('[data-zoomable]')

zoom.getZoomedImage() // => null
zoom.open().then(() => {
  zoom.getZoomedImage() // => Element
})

Attributes

data-zoom-src

Specifies the high definition image to open on zoom. This image loads when the user clicks on the source image.

<img
  src="image-thumbnail.jpg"
  data-zoom-src="image-hd.jpg"
  alt="My image"
>

Events

Event Description
open Fired immediately when the open method is called
opened Fired when the zoom has finished being animated
close Fired immediately when the close method is called
closed Fired when the zoom out has finished being animated
detach Fired when the detach method is called
update Fired when the update method is called
const zoom = mediumZoom('[data-zoomable]')

zoom.on('open', event => {
  // track when the image is zoomed
})

The zoom object is accessible in event.detail.zoom.

Examples

Trigger a zoom from another element
const button = document.querySelector('[data-action="zoom"]')
const zoom = mediumZoom('#image')

button.addEventListener('click', () => zoom.open())
Track an event (for analytics)

You can use the open event to keep track of how many times a user interacts with your image. This can be useful if you want to gather some analytics on user engagement.

let counter = 0
const zoom = mediumZoom('#image-tracked')

zoom.on('open', event => {
  console.log(`"${event.target.alt}" has been zoomed ${++counter} times`)
})
Detach a zoom once closed
const zoom = mediumZoom('[data-zoomable]')

zoom.on('closed', () => zoom.detach(), { once: true })
Attach jQuery elements

jQuery elements are compatible with medium-zoom once converted to an array.

mediumZoom($('[data-zoomable]').toArray())
Create a zoomable React component
import React, { Component } from 'react'
import mediumZoom from 'medium-zoom'

class ImageZoom extends Component {
  zoom = this.props.zoom.clone({
    background: this.props.color,
  })

  attachZoom = image => {
    this.zoom.attach(image)
  }

  render() {
    return (
      <img src={this.props.src} alt={this.props.alt} ref={this.attachZoom} />
    )
  }
}

class App extends Component {
  zoom = mediumZoom({ background: '#000', margin: 48 })

  render() {
    return (
      <ImageZoom src="image.jpg" alt="Image" zoom={this.zoom} color="#BADA55" />
    )
  }
}

You can see more examples including React and Vue, or check out the storybook.

Browser support

IE Edge Chrome Firefox Safari
10* 12* 36 34 9

* These browsers require a template polyfill when using custom templates.

Cross-browser testing is sponsored by

BrowserStack

Contributing

  • Run yarn to install Node dev dependencies
  • Run yarn start to build the library in watch mode
  • Run yarn run storybook to see your changes at http://localhost:9001

Please read the contributing guidelines for more detailed explanations.

You can also use npm.

License

MIT © François Chalifour