Skip to content

Instantly share code, notes, and snippets.

@Xiradorn
Last active October 6, 2022 23:59
Show Gist options
  • Save Xiradorn/e8872da17b3edcec1ec6b4517ac6b1c7 to your computer and use it in GitHub Desktop.
Save Xiradorn/e8872da17b3edcec1ec6b4517ac6b1c7 to your computer and use it in GitHub Desktop.
Semplistic Image Zoom Efx /w One Image - Vanilla JS
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<style type="text/css">
:root {
--x-pos: 0px;
--y-pos: 0px;
}
.container {
max-width: 900px;
display: block;
overflow: hidden;
}
.img-fluid {
max-width: 100%;
height: auto;
transition: all 200ms linear;
transform: translate(0, 0) scale(1);
}
.xzoom {
cursor: crosshair;
}
.tracker {
transform: translate(var(--x-pos), var(--y-pos)) scale(1.5);
}
</style>
</head>
<body>
<div class="container xzoom">
<img
class="img-fluid"
src="https://images.unsplash.com/photo-1506744038136-46273834b3fb?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxleHBsb3JlLWZlZWR8MXx8fGVufDB8fHx8"
alt=""
/>
</div>
<script>
/**
* Simple Zoom Image on Mouse Move
*
* @author: Xiradorn
*/
document.addEventListener("DOMContentLoaded", () => {
const cont = document.querySelector(".xzoom");
const imgEl = document.querySelector(".xzoom img");
cont.addEventListener("mousemove", (e) => {
const d = document.querySelector(":root");
const centerImg = {
x: (cont.offsetWidth / 2).toFixed(2),
y: (cont.offsetHeight / 2).toFixed(2),
};
const newPos = {
x: centerImg.x - e.clientX.toFixed(2),
y: centerImg.y - e.clientY.toFixed(2),
};
d.style.setProperty("--x-pos", newPos.x + "px");
d.style.setProperty("--y-pos", newPos.y + "px");
imgEl.classList.add("tracker");
});
cont.addEventListener("mouseleave", (e) => {
imgEl.classList.remove("tracker");
});
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment