Created
December 15, 2023 09:07
-
-
Save TheBigRoomXXL/6b0d6379e4d41860ecd93df7071c5298 to your computer and use it in GitHub Desktop.
A zoomable image with just a bit of css and js
This file contains 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
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<title>Image Loading Optimisation</title> | |
<style> | |
figure.zoom { | |
background-position: 50% 50%; | |
position: relative; | |
overflow: hidden; | |
cursor: zoom-in; | |
width: min-content; | |
/* 250% mean the zoom will be 2.5X */ | |
background-size: 250%; | |
} | |
figure.zoom img:hover { | |
opacity: 0; | |
} | |
figure.zoom img { | |
transition: opacity 0.5s; | |
display: block; | |
width: 512px; | |
} | |
</style> | |
<script> | |
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 + '%'; | |
} | |
</script> | |
</head> | |
<body> | |
<figure class="zoom" onmousemove="zoom(event)" | |
style="background-image: url(cat.webp)"> | |
<img src="cat.webp" /> | |
</figure> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment