-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
69 lines (60 loc) · 1.57 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
// ***** SELECT ELEMENTS FROM DOM *****
const slides = document.querySelectorAll('.slide');
const containerImg = document.querySelector('.img-container');
const prevBtn = document.querySelector('.prev');
const nextBtn = document.querySelector('.next');
// Confirm the index of images
let index = 0;
let percentage = 0;
// ***** EVENT LISTENERS *****
// Enables the ability to switch between images with the left and right arrow keys
window.addEventListener('keyup', function (e) {
if (e.keyCode === 37 && index > 0) {
index--;
control();
goBackImg();
} else if (e.keyCode === 39 && index < slides.length-1) {
index++;
control();
advanceImg();
}
});
// Set previous button
prevBtn.addEventListener('click', function () {
index--;
console.log(index);
control();
goBackImg();
});
// Set next button
nextBtn.addEventListener('click', function () {
index++;
console.log(index);
control();
advanceImg();
});
// Hide and show the control buttons
function control() {
if (index > 0) {
prevBtn.classList.add('show');
} else {
prevBtn.classList.remove('show');
}
if (index >= slides.length-1) {
nextBtn.classList.remove('show');
} else {
nextBtn.classList.add('show');
}
}
function advanceImg() {
percentage -= 100;
slides.forEach(sld => {
sld.style.transform = `translateX(${percentage}%)`;
});
}
function goBackImg() {
percentage += 100;
slides.forEach(sld => {
sld.style.transform = `translateX(${percentage}%)`;
});
}