|
1 | | -function Slider(slider) { |
2 | | - if (!(slider instanceof Element)) { |
3 | | - throw new Error('No slider passed in'); |
4 | | - } |
5 | | - // create some variables for working iwth the slider |
6 | | - let prev; |
7 | | - let current; |
8 | | - let next; |
9 | | - // select the elements needed for the slider |
10 | | - const slides = slider.querySelector('.slides'); |
11 | | - const prevButton = slider.querySelector('.goToPrev'); |
12 | | - const nextButton = slider.querySelector('.goToNext'); |
13 | | - |
14 | | - function startSlider() { |
15 | | - current = slider.querySelector('.current') || slides.firstElementChild; |
16 | | - prev = current.previousElementSibling || slides.lastElementChild; |
17 | | - next = current.nextElementSibling || slides.firstElementChild; |
18 | | - console.log({ current, prev, next }); |
19 | | - } |
20 | | - |
21 | | - function applyClasses() { |
22 | | - current.classList.add('current'); |
23 | | - prev.classList.add('prev'); |
24 | | - next.classList.add('next'); |
25 | | - } |
26 | | - |
27 | | - function move(direction) { |
28 | | - // first strip all the classes off the current slides |
29 | | - const classesToRemove = ['prev', 'current', 'next']; |
30 | | - prev.classList.remove(...classesToRemove); |
31 | | - current.classList.remove(...classesToRemove); |
32 | | - next.classList.remove(...classesToRemove); |
33 | | - if (direction === 'back') { |
34 | | - // make an new array of the new values, and destructure them over and into the prev, current and next variables |
35 | | - [prev, current, next] = [ |
36 | | - // get the prev slide, if there is none, get the last slide from the entire slider for wrapping |
37 | | - prev.previousElementSibling || slides.lastElementChild, |
38 | | - prev, |
39 | | - current, |
40 | | - ]; |
41 | | - } else { |
42 | | - [prev, current, next] = [ |
43 | | - current, |
44 | | - next, |
45 | | - // get the next slide, or if it's at the end, loop around and grab the first slide |
46 | | - next.nextElementSibling || slides.firstElementChild, |
47 | | - ]; |
48 | | - } |
49 | | - |
50 | | - applyClasses(); |
51 | | - } |
52 | | - |
53 | | - // when this slider is created, run the start slider function |
54 | | - startSlider(); |
55 | | - applyClasses(); |
56 | | - |
57 | | - // Event listeners |
58 | | - prevButton.addEventListener('click', () => move('back')); |
59 | | - nextButton.addEventListener('click', move); |
60 | | -} |
61 | | - |
62 | | -const mySlider = Slider(document.querySelector('.slider')); |
63 | | -const dogSlider = Slider(document.querySelector('.dog-slider')); |
0 commit comments