Javascript for image zoom

Image Zoom on Hover using Javascript (Code + Demo)

In this article you will learn how to create Zoom Image on hover using JavaScript. Zoom Image is created in many ways. If you want, you can also add zoom effect in the middle of an image image just by html. The design made here is JavaScript Image zoom on hover. Since JavaScript is used here, it is very advanced. You can zoom in on every point of the image in this project. ✅✅ Live Preview 👉 JavaScript Image Zoom Basically it will follow your mouse cursor. As a result, the part of the image where you move the mouse will be zoomed in. But it is not possible to just zoom the image with css.

Javascript Image Zoom on Hover

First I made a box. Then I added an image in that box. A border of box height: 300px , width: 500px and 5px has been used. The image has been made equal to the size of the box. You need to follow 3 steps to create it. Below I have given all the code. However, I have shared the explanation with each of those code lines have been used.

HTML Code

  • Image has been added using ‘background-image’ in ‘figure’ first.
  • Image has been added to the img tag later.
  • Here onmousemove = «zoom (event)» is used. As a result, if you move the mouse over the image, the image will zoom.
  • Here only the image in ‘figure’ will be zoomed. Images added using Imgre tags will not change.
Читайте также:  How to save json file python

Below are two images that have been used and what they do.

 class="zoom" onmousemove="zoom(event)" style="background-image: url(https://images5.alphacoders.com/343/thumb-1920-343645.jpg)">  src="https://images5.alphacoders.com/343/thumb-1920-343645.jpg" />  

CSS Code

Now it is time to design Zoom Image on hover by css.

  • First the basic design of ‘figure’ has been done. Box height: 300px , width: 500px
  • Then I added the hover effect in the Norman image (img: hover) . Here opacity: 0 is used using hover. As a result, if you move the mouse inside the box, the image added by the img tag will not be visible.
  • Since the image using the img tag cannot be seen, the image in the ‘figure’ on the back can be seen.
figure.zoom  background-position: 50% 50%; position: relative; margin: 150px auto; border: 5px solid white; box-shadow: -1px 5px 15px black; height: 300px; width: 500px; overflow: hidden; cursor: zoom-in; > figure.zoom img:hover  opacity: 0; > figure.zoom img  transition: opacity 0.5s; display: block; width: 100%; height: 100%; > 

JavaScript Code

Almost all the work of design is made. Now it’s time to activate this Zoom Image by JavaScript. JavaScript basically helps to follow the mouse cursor.

function zoom(e) var zoomer = e.currentTarget; e.offsetX ? offsetX = e.offsetX : offsetX = e.touches[0].pageX e.offsetY ? offsetY = e.offsetY : offsetX = e.touches[0].pageX x = offsetX/zoomer.offsetWidth*100 y = offsetY/zoomer.offsetHeight*100 zoomer.style.backgroundPosition = x + '% ' + y + '%'; > 

Please comment on how you like this javascript image zoom on hover. If there is any problem, please comment. I have created many image zoom effects using css.

Hopefully you have learned from this article how to Zoom Image on hover using JavaScript.

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

🔎 🖼 A JavaScript library for zooming images like Medium

License

francoischalifour/medium-zoom

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

A JavaScript library for zooming images like Medium

  • 📱 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.

The module is available on the npm registry.

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

Import the library as a module:

import mediumZoom from 'medium-zoom'

Or import the library with a script tag:

script src pl-s">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(selector?: string | HTMLElement | HTMLElement[ ] | NodeList, options?: object): Zoom

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)

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 | HTMLElement | object null The viewport to render the zoom in
Read more →
template string | HTMLTemplateElement 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', >)

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.

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.

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.

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() // =>

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 .

Returns the zoom options as an object.

const zoom = mediumZoom( background: '#BADA55' >) zoom.getOptions() // =>

Returns the images attached to the zoom as an array of HTMLElement s.

const zoom = mediumZoom('[data-zoomable]') zoom.getImages() // => [HTMLElement, 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 >)

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

img src pl-s">image-thumbnail.jpg" data-zoom-src pl-s">image-hd.jpg" alt pl-s">My image" />
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 .

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:

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.

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; >

Cross-browser testing is sponsored by

  • 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.

Источник

Оцените статью