-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
78 lines (67 loc) · 2.27 KB
/
index.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
let carouselElements
let carouselContainer
let arrowLeftElement
let arrowRightElement
let currentElement
export default function({container, elements, arrowLeft, arrowRight}) {
carouselContainer = container
carouselElements = Array.from(elements)
arrowLeftElement = arrowLeft
arrowRightElement = arrowRight
currentElement = carouselElements[0]
carouselContainer.style = `
display:flex;
justify-content: flex-start;
flex-wrap:nowrap;
overflow:hidden;`
if (carouselContainer.clientWidth > carouselContainer.scrollWidth) return
updateButtons()
arrowLeftElement.addEventListener('click', scrollToLeft)
arrowRightElement.addEventListener('click', scrollToRight)
carouselContainer.addEventListener('scroll', updateButtons)
}
function scrollToLeft() {
carouselContainer.scroll({
left: carouselContainer.scrollLeft - getWidthPlusPaddingAndMargin(currentElement),
behavior: 'smooth'
})
backPointer()
}
function scrollToRight() {
carouselContainer.scroll({
left: carouselContainer.scrollLeft + getWidthPlusPaddingAndMargin(currentElement),
behavior: 'smooth'
})
advancePointer()
}
function updateButtons() {
arrowLeftElement.disabled = false
arrowRightElement.disabled = false
if (!carouselContainer.scrollLeft) {
arrowLeftElement.disabled = true
} else if (scrolledDistance() === carouselContainer.scrollWidth) {
arrowRightElement.disabled = true
}
}
function advancePointer() {
let index = carouselElements.indexOf(currentElement)
if(index < carouselElements.length - 1) {
currentElement = carouselElements[++index]
}
}
function backPointer() {
let index = carouselElements.indexOf(currentElement)
if(index > 0) {
currentElement = carouselElements[--index]
}
}
function scrolledDistance() {
return carouselContainer.clientWidth + carouselContainer.scrollLeft
}
function getWidthPlusPaddingAndMargin(element) {
return parseFloat(window.getComputedStyle(element).width) +
parseFloat(window.getComputedStyle(element).paddingLeft) +
parseFloat(window.getComputedStyle(element).paddingRight) +
parseFloat(window.getComputedStyle(element).marginLeft) +
parseFloat(window.getComputedStyle(element).marginRight)
}