1.1.0 β€’ Published 5 months ago

medium-zoom v1.1.0

Weekly downloads
44,920
License
MIT
Repository
github
Last release
5 months ago

Features

  • πŸ“± Responsive β€” scale on mobile and desktop
  • πŸš€ Performant and lightweight β€” optimized 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
  • πŸ”Œ Framework agnostic β€” works with React, Vue, Angular, Svelte, Solid, etc.

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.

Assuming you add the data-zoomable attribute to your images:

mediumZoom('[data-zoomable]')

!TIP If you want to control when to inject the Medium Zoom CSS styles, you can use the pure JavaScript bundle:

import mediumZoom from 'medium-zoom/dist/pure'
import 'medium-zoom/dist/style.css'

API

mediumZoom(selector?: string | HTMLElement | HTMLElement[] | NodeList, options?: object): Zoom

Selectors

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

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

// HTMLElement
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:

PropertyTypeDefaultDescription
marginnumber0The space outside the zoomed image
backgroundstring"#fff"The background of the overlay
scrollOffsetnumber40The number of pixels to scroll to close the zoom
containerstring | HTMLElement | objectnullThe viewport to render the zoom in Read more β†’
templatestring | HTMLTemplateElementnullThe 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?: HTMLElement }): 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?: HTMLElement }): 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[] | HTMLElement[] | 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[] | HTMLElement[] | 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: () => void, options?: boolean | AddEventListenerOptions): 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: () => void, options?: boolean | AddEventListenerOptions): 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(): HTMLElement[]

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

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

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

getZoomedImage(): HTMLElement

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

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

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

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

EventDescription
openFired immediately when the open method is called
openedFired when the zoom has finished being animated
closeFired immediately when the close method is called
closedFired when the zoom out has finished being animated
detachFired when the detach method is called
updateFired 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.

Framework integrations

Medium Zoom is a JavaScript library that can be used with any framework. Here are some integrations that you can use to get started quickly:

Examples

const button = document.querySelector('[data-action="zoom"]')
const zoom = mediumZoom('#image')

button.addEventListener('click', () => zoom.open())

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`)
})
const zoom = mediumZoom('[data-zoomable]')

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

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

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

export function ImageZoom({ options, ...props }) {
  const zoomRef = useRef(null)

  function getZoom() {
    if (zoomRef.current === null) {
      zoomRef.current = mediumZoom(options)
    }

    return zoomRef.current
  }

  function attachZoom(image) {
    const zoom = getZoom()

    if (image) {
      zoom.attach(image)
    } else {
      zoom.detach()
    }
  }

  return <img {...props} ref={attachZoom} />
}

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

Debugging

The zoomed image is not visible

The library doesn't provide a z-index value on the zoomed image to avoid conflicts with other frameworks. Some frameworks might specify a z-index for their elements, which makes the zoomed image not visible.

If that's the case, you can provide a z-index value in your CSS:

.medium-zoom-overlay,
.medium-zoom-image--opened {
  z-index: 999;
}

Browser support

IEEdgeChromeFirefoxSafari
10*12*36349

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

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

gatsby-universalmedium-zoom-vuedocusaurus-image-zoom@kvass/template-gallerysaber-plugin-medium-zoom@infinitebrahmanuniverse/nolb-medigatsby-sciplay-pkg@everything-registry/sub-chunk-2151@flicmd/bytemd-plugin-medium-zoom@beanjs/docutespencerpaulynotionxspx-private@deboxsoft/svelte-markdown@deboxsoft/bytemd-plugin-medium-zoom@deboxsoft/bytemd-sveltekit@developerportalsg/docsifyhexo-butterfly-extjsumbertovalaxyvite-plugin-vitepress-medium-zoomhexo-theme-cake@cyrus25/react-notion-xgatsby-theme-yoshinogatsby-remark-images-medium-zoomgatsby-remark-images-zoomgatsby-starter-datocms@bryce-loskie/mz@bytemd/plugin-medium-zoomsaikavorto-dashboardvitepress-shopware-docsvue3-google-login-with-statevuepress-rc-plugin-medium-zoomvuepress-plugin-medium-zoomvuepress-theme-uphgvue-image-viewer-mzislandjs@cryogenicplanet/react-notion-x@teochengyong/docsify@stellar-design/core@thinkvn/tiptap@floatsheep/tg-talker@uuz.io/react-notion-xblitz-libsblueprint-hooks-uicustomized-react-notion-xdocsify-highlightdocsify-expanddocsify-patcheddocsifydocutedocute-fadoczifydocusaurus-plugin-enlarge-imagedocusaurus-plugin-image-zoomdocusaurus-plugin-medium-zoom@yelo/saber-plugin-medium-zoom@vuepress/plugin-medium-zoomcolored-react-notion-xdante3react-saasifykodama-uilcap_markdown_doc_render_viewmd-editor-rtmd-editor-v3medium-zoom-element@jchavarri/docsify@iyucode/md-editor@kdupress/plugin-medium-zoom@kosmotema/bytemd-plugin-medium-zoom@halka/react-medium-zoompugin-fonts@nkduy/plugin-medium-zoom@next-theme/plugins@pcd/passport-uipicidae-transformer-medium-image-zoom@pitayan/gatsby-theme-pitayan@pinpt/reactplugin-image-zoom@mx-space/kami-designnotion-forge@mdpress/plugin-medium-zoom@markspec/vuepress-plugin-imagequ-admin-plus@rspress/plugin-medium-zoom@schickling-tmp/react-notion-x@midwest-design/medianuxt-archnuxt-arch-dev@lume/docsify@modern-js/doc-plugin-medium-zoom@saasify/docsifyproton-docs@skrey/v-directivereact-medium-zoomreact-notion-emailreact-notion-x-customreact-notion-yreact-notioner
1.1.0

5 months ago

1.0.8

1 year ago

1.0.7

1 year ago

1.0.6

4 years ago

1.0.5

4 years ago

1.0.4

5 years ago

1.0.3

5 years ago

1.0.2

6 years ago

1.0.1

6 years ago

1.0.0

6 years ago

1.0.0-next.0

6 years ago

0.4.0

6 years ago

0.3.0

6 years ago

0.2.0

7 years ago

0.1.8

7 years ago

0.1.7

7 years ago

0.1.6

7 years ago

0.1.5

7 years ago

0.1.4

7 years ago

0.1.3

7 years ago

0.1.2

7 years ago

0.1.1

8 years ago

0.1.0

8 years ago