| Author: | Den McHenry |
|---|---|
| Views Total: | 16,741 views |
| Official Page: | Go to website |
| Last Update: | March 19, 2018 |
| License: | MIT |
Preview:

Description:
Detail View is a vanilla JavaScript approach to zooming and panning an image on hover.
How to use it:
Add your image as a background to the element with the class of ‘detail-view’.
<div class="detail-view" style="background-image: url(image.jpg);"></div>
Get all images with the ‘detail-view’ class.
var zoomBoxes = document.querySelectorAll('.detail-view');The main JavaScript to active the image zoom & pan functionalities.
// Extract the URL
zoomBoxes.forEach(function(image) {
var imageCss = window.getComputedStyle(image, false),
imageUrl = imageCss.backgroundImage
.slice(4, -1).replace(/['"]/g, '');
// Get the original source image
var imageSrc = new Image();
imageSrc.onload = function() {
var imageWidth = imageSrc.naturalWidth,
imageHeight = imageSrc.naturalHeight,
ratio = imageHeight / imageWidth;
// Adjust the box to fit the image and to adapt responsively
var percentage = ratio * 100 + '%';
image.style.paddingBottom = percentage;
// Zoom and scan on mousemove
image.onmousemove = function(e) {
// Get the width of the thumbnail
var boxWidth = image.clientWidth,
// Get the cursor position, minus element offset
x = e.pageX - this.offsetLeft,
y = e.pageY - this.offsetTop,
// Convert coordinates to % of elem. width & height
xPercent = x / (boxWidth / 100) + '%',
yPercent = y / (boxWidth * ratio / 100) + '%';
// Update styles w/actual size
Object.assign(image.style, {
backgroundPosition: xPercent + ' ' + yPercent,
backgroundSize: imageWidth + 'px'
});
};
// Reset when mouse leaves
image.onmouseleave = function(e) {
Object.assign(image.style, {
backgroundPosition: 'center',
backgroundSize: 'cover'
});
};
}
imageSrc.src = imageUrl;
});







Hello, thank you for sharing this how-to – I have been looking for this for ages! I am struggling to understand and implement this on my squarespace website. Are you able to explain how to use this function more step-by-step/ simpler? I am not overly used to coding language.
Is it possible to use a foreground image instead of a background one? How?