-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmagnify.js
63 lines (53 loc) · 2.08 KB
/
magnify.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// create a container and set the full-size image as its background
function createOverlay(image) {
const overlayImage = document.createElement('img');
overlayImage.setAttribute('src', `${image.src}`);
overlay = document.createElement('div');
prepareOverlay(overlay, overlayImage);
image.style.opacity = '50%';
toggleLoadingSpinner(image);
overlayImage.onload = () => {
toggleLoadingSpinner(image);
image.parentElement.insertBefore(overlay, image);
image.style.opacity = '100%';
};
return overlay;
}
function prepareOverlay(container, image) {
container.setAttribute('class', 'image-magnify-full-size');
container.setAttribute('aria-hidden', 'true');
container.style.backgroundImage = `url('${image.src}')`;
container.style.backgroundColor = 'var(--gradient-background)';
}
function toggleLoadingSpinner(image) {
const loadingSpinner = image.parentElement.parentElement.querySelector(`.loading__spinner`);
loadingSpinner.classList.toggle('hidden');
}
function moveWithHover(image, event, zoomRatio) {
// calculate mouse position
const ratio = image.height / image.width;
const container = event.target.getBoundingClientRect();
const xPosition = event.clientX - container.left;
const yPosition = event.clientY - container.top;
const xPercent = `${xPosition / (image.clientWidth / 100)}%`;
const yPercent = `${yPosition / ((image.clientWidth * ratio) / 100)}%`;
// determine what to show in the frame
overlay.style.backgroundPosition = `${xPercent} ${yPercent}`;
overlay.style.backgroundSize = `${image.width * zoomRatio}px`;
}
function magnify(image, zoomRatio) {
const overlay = createOverlay(image);
overlay.onclick = () => overlay.remove();
overlay.onmousemove = (event) => moveWithHover(image, event, zoomRatio);
overlay.onmouseleave = () => overlay.remove();
}
function enableZoomOnHover(zoomRatio) {
const images = document.querySelectorAll('.image-magnify-hover');
images.forEach((image) => {
image.onclick = (event) => {
magnify(image, zoomRatio);
moveWithHover(image, event, zoomRatio);
};
});
}
enableZoomOnHover(2);