Last active
December 6, 2024 20:57
-
-
Save laundmo/341526bd819c619712e2680a4469cd7f to your computer and use it in GitHub Desktop.
JS function which makes a html image zoomable by hovering over it. Licensed MIT
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Makes an HTML image zoomable on hover. Requires the img to be nested in a container of the same size. | |
* Uses transform for the actual zoom behaviour. | |
* | |
* @param {HTMLElement} elem - The HTML element of the image to make zoomable. | |
* @param {number} scale - The zoom scale factor. | |
* @param {number} [margin=0.2] - The margin around the zoomed image, as a fraction of the image. Helps with seeing the edges. | |
* @returns {void} | |
* | |
* @example | |
* makeElementHoverZoomable(document.getElementById('zoomable-img'), 2); | |
*/ | |
function makeImageHoverZoomable(elem, scale, margin = 0.2){ | |
let events_on = elem.parentNode; | |
const margin_mult = 1 + margin; | |
// set transform-origin of elem to the mouse x,y | |
events_on.addEventListener("pointermove", (e) => { | |
const rect = e.currentTarget.getBoundingClientRect(); | |
// get x,y of cursor on rect | |
let x = Math.floor(e.clientX - rect.x); | |
let y = Math.floor(e.clientY - rect.y); | |
// get midpoint of rect | |
let x_mid = rect.width / 2; | |
let y_mid = rect.height / 2; | |
// combine with margin and midpoint for scaling how far mouse moves | |
x = -((x - x_mid) * margin_mult / x_mid) * 100; | |
y = -((y - y_mid) * margin_mult / y_mid) * 100; | |
elem.style.transform = `translate(${x}%, ${y}%) scale(${scale})`; | |
e.stopImmediatePropagation(); | |
}, true); | |
// clear and reset transform | |
events_on.addEventListener("pointerleave", (e) => { | |
elem.style.transform = ""; | |
}, true) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment