Convert Figma logo to code with AI

francoischalifour logomedium-zoom

🔎🖼 A JavaScript library for zooming images like Medium

3,623
165
3,623
45

Top Related Projects

26,486

Animate on scroll library

JavaScript image gallery for mobile and desktop, modular, framework independent

:camera: JavaScript is all like "You images done yet or what?"

1,543

jQuery plugin for zooming images on mouseover.

Javascript library to help creating high quality justified galleries of images. Used by thousands of websites as well as the photography community 500px.

Quick Overview

Medium-zoom is a lightweight JavaScript library that adds a zoom effect to images, similar to the one used on Medium.com. It provides a smooth and customizable zooming experience for images on web pages, enhancing user interaction and visual appeal.

Pros

  • Easy to implement with minimal setup
  • Customizable options for zoom behavior and styling
  • Supports both vanilla JavaScript and various frameworks (React, Vue, etc.)
  • Lightweight and performant

Cons

  • Limited to image zooming functionality only
  • May not be necessary for simple websites with few images
  • Requires JavaScript to function, which may impact accessibility for users with JS disabled

Code Examples

  1. Basic usage:
import mediumZoom from 'medium-zoom'

mediumZoom('img')

This code applies the zoom effect to all <img> elements on the page.

  1. Customizing zoom options:
mediumZoom('img', {
  margin: 24,
  background: '#BADA55',
  scrollOffset: 0,
  container: '#zoom-container'
})

This example demonstrates how to customize the zoom behavior with specific options.

  1. Using with React:
import React, { useEffect, useRef } from 'react'
import mediumZoom from 'medium-zoom'

function ZoomableImage({ src, alt }) {
  const imgRef = useRef(null)

  useEffect(() => {
    mediumZoom(imgRef.current)
  }, [])

  return <img ref={imgRef} src={src} alt={alt} />
}

This code shows how to integrate medium-zoom with a React component.

Getting Started

  1. Install the library:
npm install medium-zoom
  1. Import and use in your JavaScript file:
import mediumZoom from 'medium-zoom'

// Apply zoom to all images
mediumZoom('img')

// Or apply to specific images
mediumZoom('.zoomable-image')
  1. Make sure your HTML includes the images you want to zoom:
<img src="image.jpg" alt="Zoomable Image" class="zoomable-image">

That's it! Your images should now have the zoom effect when clicked.

Competitor Comparisons

26,486

Animate on scroll library

Pros of AOS

  • More versatile, offering various animation effects for multiple elements
  • Supports both scroll-triggered and initial load animations
  • Highly customizable with numerous options and data attributes

Cons of AOS

  • Larger file size and potentially higher performance impact
  • May require more setup and configuration for complex animations
  • Not specifically optimized for image zooming functionality

Code Comparison

AOS initialization:

AOS.init({
  duration: 1000,
  easing: 'ease-in-out',
  once: true
});

medium-zoom initialization:

mediumZoom('img', {
  margin: 24,
  background: '#BADA55',
  scrollOffset: 0
});

Key Differences

  • AOS is a general-purpose animation library for scroll effects, while medium-zoom focuses specifically on image zooming
  • AOS requires more setup but offers broader functionality, whereas medium-zoom is more plug-and-play for its specific use case
  • medium-zoom is lighter and more performant for image zooming, while AOS provides a wider range of animation options

Both libraries serve different purposes and can be used together in a project if needed. AOS is better suited for overall page animations, while medium-zoom excels at providing a smooth image zoom experience.

JavaScript image gallery for mobile and desktop, modular, framework independent

Pros of PhotoSwipe

  • More feature-rich, offering a full-fledged gallery experience with thumbnails, captions, and sharing options
  • Supports touch gestures and mobile-friendly interactions
  • Highly customizable with extensive API and theming options

Cons of PhotoSwipe

  • Larger file size and more complex implementation compared to medium-zoom
  • Steeper learning curve due to its extensive features and options
  • May be overkill for simple image zooming needs

Code Comparison

PhotoSwipe initialization:

var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, options);
gallery.init();

medium-zoom initialization:

mediumZoom('img');

Summary

PhotoSwipe is a comprehensive image gallery solution with advanced features, while medium-zoom focuses solely on image zooming. PhotoSwipe offers more functionality but comes with increased complexity, while medium-zoom provides a simpler, lightweight solution for basic image zooming needs. The choice between the two depends on the specific requirements of your project and the level of functionality you need for image presentation.

:camera: JavaScript is all like "You images done yet or what?"

Pros of imagesloaded

  • Focuses specifically on detecting when images have finished loading
  • Supports a wider range of image loading scenarios (e.g., background images, broken images)
  • More mature project with longer development history and wider adoption

Cons of imagesloaded

  • Limited to image loading functionality, doesn't provide zooming capabilities
  • Larger file size due to broader feature set
  • May require additional libraries or code for advanced image interactions

Code Comparison

imagesloaded:

imagesLoaded( elem, callback )
// or
imagesLoaded( elem ).on( 'always', callback )

medium-zoom:

mediumZoom('img')
// or
mediumZoom(document.querySelector('img'))

Key Differences

  • Purpose: imagesloaded focuses on detecting image load completion, while medium-zoom provides image zooming functionality
  • Scope: imagesloaded has a broader scope for image loading scenarios, medium-zoom is specifically for zooming
  • Usage: imagesloaded is typically used for managing page load and layout, medium-zoom enhances image viewing experience
  • Dependencies: imagesloaded is standalone, medium-zoom may require additional CSS for styling

Conclusion

Choose imagesloaded for robust image loading detection across various scenarios. Opt for medium-zoom if you need a lightweight solution specifically for image zooming functionality. Consider using both in combination for a comprehensive image handling solution in web applications.

1,543

jQuery plugin for zooming images on mouseover.

Pros of zoom

  • Lightweight and simple implementation
  • Supports both inline and external images
  • Works with responsive images and various CSS scenarios

Cons of zoom

  • Less actively maintained (last update in 2018)
  • Fewer customization options
  • Limited browser support for older versions

Code Comparison

medium-zoom:

mediumZoom('img', {
  margin: 24,
  background: '#BADA55',
  scrollOffset: 0,
  container: '#zoom-container',
  template: '#zoom-template'
});

zoom:

$('img').zoom({
  url: 'photo-big.jpg',
  on: 'grab',
  magnify: 2
});

Key Differences

  • medium-zoom is more actively maintained and has better documentation
  • medium-zoom offers more customization options and a more modern API
  • zoom is simpler to implement for basic use cases
  • medium-zoom has better performance for large numbers of images
  • zoom relies on jQuery, while medium-zoom is a standalone library

Both libraries provide image zooming functionality, but medium-zoom offers a more robust and modern solution with additional features and customization options. zoom might be preferable for simpler projects or those already using jQuery, while medium-zoom is better suited for larger, more complex applications requiring fine-tuned control over the zooming behavior.

Javascript library to help creating high quality justified galleries of images. Used by thousands of websites as well as the photography community 500px.

Pros of Justified-Gallery

  • Focuses on creating beautiful, justified image galleries
  • Supports multiple row layouts and customizable margins
  • Includes built-in lightbox functionality

Cons of Justified-Gallery

  • Limited to image galleries, less versatile for other content types
  • Requires more setup and configuration for basic usage
  • Larger file size due to additional features

Code Comparison

Justified-Gallery:

$('#gallery').justifiedGallery({
    rowHeight: 200,
    lastRow: 'nojustify',
    margins: 3
});

medium-zoom:

mediumZoom('img', {
    margin: 24,
    background: '#000',
    scrollOffset: 0
});

Summary

Justified-Gallery is a specialized library for creating visually appealing image galleries with justified layouts. It offers more features for gallery creation but is less versatile compared to medium-zoom. medium-zoom, on the other hand, provides a simpler, more focused solution for image zooming functionality that can be applied to various content types. The choice between the two depends on the specific needs of the project, with Justified-Gallery being better suited for complex image gallery layouts and medium-zoom for general image zoom functionality.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Demo

medium-zoom

A JavaScript library for zooming images like Medium

version MIT license downloads
gzip size no dependencies

Medium Zoom Demo

🔬 Playground ・ 🔎 Demo ・ 📚 Storybook

Contents

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

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, { 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.

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

NPM DownloadsLast 30 Days