-
Notifications
You must be signed in to change notification settings - Fork 0
/
slider.js
91 lines (72 loc) · 2.28 KB
/
slider.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
const slider = document.querySelector('.slider-container');
const slides = Array.from(document.querySelectorAll('.slide'));
let isDragging = false,
startPos = 0,
currentTranslate = 0,
prevTranslate = 0,
animationID = 0,
currentIndex = 0
slides.forEach((slide,index) =>{
const slideImage = slide.querySelector('img');
slideImage.addEventListener('dragstart', e => e.preventDefault());
// Touch events
slide.addEventListener('touchstart', touchStart(index))
slide.addEventListener('touchend', touchEnd)
slide.addEventListener('touchmove', touchMove)
// Mouse events
slide.addEventListener('mousedown', touchStart(index))
slide.addEventListener('mouseup', touchEnd)
slide.addEventListener('mouseleave', touchEnd)
slide.addEventListener('mousemove', touchMove)
})
//disable context menu
window.oncontextmenu = function (event) {
event.preventDefault();
event.stopPropagation();
return false;
}
function touchStart(index) {
return function(event){
currentIndex = index;
startPos = getPositionX(event);
isDragging = true;
animationID = requestAnimationFrame(animation);
slider.classList.add('grabbing');
}
}
function touchEnd() {
isDragging = false;
cancelAnimationFrame(animationID);
const movedBy = currentTranslate - prevTranslate;
if(movedBy < -100 && currentIndex < slides.length-1){
currentIndex+=1;
}
if(movedBy > 100 && currentIndex > 0) currentIndex-=1;
setPositionByIndex();
slider.classList.remove('grabbing');
}
function touchMove() {
if(isDragging) {
const currentPosition = getPositionX(event);
currentTranslate = prevTranslate + currentPosition - startPos;
}
}
function getPositionX(event) {
return event.type.includes('mouse') ? event.pageX : event.touches[0].clientX;
}
function animation() {
setSliderPosition();
if(isDragging) requestAnimationFrame(animation)
}
function setSliderPosition() {
slider.style.transform = `translateX(${currentTranslate}px)`;
}
function setPositionByIndex() {
if(window.matchMedia('(max-width:700px').matches){
currentTranslate = currentIndex * -100;
} else{
currentTranslate = currentIndex * -300;
}
prevTranslate = currentTranslate;
setSliderPosition();
}