-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrotation.js
More file actions
61 lines (51 loc) · 2.32 KB
/
rotation.js
File metadata and controls
61 lines (51 loc) · 2.32 KB
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
class Image360Rotation {
constructor({ identifier, speed = 50, reversed = false, startingImageIndex = 0 }) {
this.identifier = identifier;
this.speed = speed;
this.reversed = reversed;
this.rotationContainer = document.querySelector(`#${this.identifier}`);
this.imageElements = [...this.rotationContainer.querySelectorAll(`#${this.identifier} img`)];
this.xLocLocked = 0;
this.imageElements.forEach((el) => {
el.setAttribute('draggable', false);
el.dataset.focused = '0';
});
this.imageElements[startingImageIndex].dataset.focused = '1';
this.onRotate = this.onRotate.bind(this);
this.rotationContainer.addEventListener('mousedown', (event) => {
event.preventDefault();
this.xLocLocked = event.screenX;
const stop = () => this.rotationContainer.removeEventListener('mousemove', this.onRotate);
this.rotationContainer.addEventListener('mousemove', this.onRotate);
this.rotationContainer.addEventListener('mouseup', stop, { once: true });
this.rotationContainer.addEventListener('mouseleave', stop, { once: true });
});
}
updateFocus(index) {
this.imageElements.forEach((image) => {
image.dataset.focused = image === this.imageElements.at(index) ? '1' : '0';
image.dataset.focused === '1' ? (image.style.visibility = 'visible') : (image.style.visibility = 'hidden');
});
}
onRotate(e) {
const xLoc = e.screenX;
const delta = Math.abs(xLoc - this.xLocLocked);
if (delta < this.speed) return;
const direction = this.reversed ? (xLoc < this.xLocLocked ? -1 : 1) : xLoc > this.xLocLocked ? -1 : 1;
const currIndex = this.imageElements.findIndex((i) => i.dataset.focused === '1');
const newIndex = currIndex + direction > [...this.imageElements].length - 1 ? 0 : currIndex + direction;
this.updateFocus(newIndex);
this.xLocLocked = xLoc; // reset locked location to prevent fast skipping of images
}
}
// Examples. Add your containers with the corresponding IDs here.
new Image360Rotation({
identifier: 'rotation-1',
speed: 15,
reversed: false,
});
new Image360Rotation({
identifier: 'rotation-2',
speed: 5,
reversed: true,
});