CSS&JS/⚡Thinkers

[JS]바닐라 자바스크립트로 slick slider 간단히 구현해보기

arancia_ 2023. 1. 20. 10:54

See the Pen Like Slick Slider by Oh Ikmyeong (@dpffpself) on CodePen.

데모 및 코드 소스 코드펜에서 확인하기  : https://codepen.io/dpffpself/pen/dyjJbqo

 

Like Slick Slider

...

codepen.io

 

HTML

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
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>slick slider vanilla js</title>
    <link rel="stylesheet" href="./style.css">
    <script src="./main.js" defer></script>
</head>
<body>
    <h1>Like Slick Slider</h1>
    <ul class="lss" id="test">
        <li class="lss-item">
            <h1>(1)Hello World</h1>
            <button>button</button>
        </li>
        <li class="lss-item">
            <h2>Item(2)</h2>
        </li>
        <li class="lss-item">
            <h2>....(3)</h2>
        </li>
        <li class="lss-item">
            <h2>4</h2>
        </li>
    </ul>
    <footer>Thank you</footer>
</body>
</html>
cs

CSS

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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
@charset "utf-8";
:root{
    --wid-lss:1200px;
    --hei-lss:600px;
}
 
*{margin:0;padding:0;box-sizing:border-box;}
li{list-style-type:none;}
button{cursor:pointer; font-size:inherit;}
 
body{
    display:flex;flex-flow:column nowrap;
    justify-content:center; align-items:center;
    gap:5vmax;
    min-height:100vh; background:#ccc;
    font-size:20px;
}
 
/* wrapper */
.wrap-lss{
    position:relative; overflow:hidden;
    width:var(--wid-lss); max-width:100vw;
    height:600px;
    background:#fff;
}
 
/* slider */
.lss{
    display:flex;
    justify-content:flex-start;
    position:relative;
    height:100%;
    transition:transform .5s linear;
}
 
.lss.off{transition:none;}
 
.lss-item{
    flex:none;
    display:flex; flex-flow: column nowrap;
    justify-content:center; align-items:center;
    gap:20px;
    position:relative; overflow:hidden;
    width:var(--wid-lss); max-width:100vw; height:var(--hei-lss);
    background:#fff;
    border:1px solid black;
    user-select:none;
}
 
/* pager */
.lss-pager{
    display:flex;flex-flow:row nowrap;
    position:absolute;
    left:0; bottom:0px;
    width:100%;
}
.lss-pager button{
    display:block; position:relative;
    width:var(--wid-btn); height:14px;
    padding:0;
    background:#eee;
    border:1px solid #ccc;
    transition:background .2s linear;
}
 
.lss-pager button.on{
    background:dodgerblue;
}
 
.lss-pager button:hover{
    filter:brightness(80%);
}
 
/* prev, next button */
.lss-btn-prev,
.lss-btn-next{
    display:block;position:absolute;
    width:40px; aspect-ratio:1/2;
    padding:0;
    top:50%; transform:translateY(-50%);
}
 
.lss-btn-prev{
    left:0;
}
.lss-btn-next{
    right:0;
}
 
.lss-btn-prev::before,
.lss-btn-next::before{
    content:'';display:block;position:absolute;
    box-sizing:border-box;
    width:15px; aspect-ratio:1/1;
    top:50%; transform:translate(-50%,-50%) rotate(45deg);
    border:3px solid black;
    pointer-events:none;
}
 
.lss-btn-prev::before{
    left:55%;
    border-width:0 0 3px 3px;
}
 
.lss-btn-next::before{
    left:45%;
    border-width:3px 3px 0 0;
}
cs

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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
class LssBuilder{
    set_selector(selector){
        this.selector = selector;
        return this;
    }
 
    is_pager(bool){
        this.isPager = bool;
        return this;
    }
 
    is_btns(bool){
        this.isBtns = bool;
        return this;
    }
 
    init(){
        return new LikeSlickSlider(this);
    }
}//class-LssBuilder
 
class LikeSlickSlider{
    constructor(Builder){
        this.selector = Builder?.selector;
        this.isPager = Builder?.isPager ?? false;
        this.isBtns = Builder?.isBtns ?? false;
        this.$wrap = null;
        this.$lss = null;
        this.$pager = null;
        this.$btns = [];
 
        this.widSlider = null;
        this.IDX = 0;
        this.COUNT = null;
        this.POS = {prev : null, curr:null};
    }//constructor
 
    /** make lss */
    init(){
        //DOM 생성
        this.make_wrap();
        this.isPager && this.make_pager();
        this.isBtns && this.make_btns();
 
        //첫번째와 마지막 아이템을 추가한다
        this.add_copy_item_first_last();
 
        //슬라이드 가로 사이즈 설정
        this.set_wid_slider();
 
        //첫번째 슬라이드가 보이도록 이동시킨다
        this.off_transition();
        this.move_slider();
        this.on_transition();
 
        /* 이벤트 추가 */
        //리사이즈시 슬라이드 가로 사이즈 재 설정
        window.addEventListener('resize'this.set_wid_slider);
 
        //버튼 이벤트 추가
        this.isBtns && this.add_btn_event();
 
        //페이저 이벤트 추가
        this.isPager && this.add_pager_event();
 
        //마우스,터치 이벤트 추가
        this.add_mouse_touch_event();
    }//init
 
    /** 
     * $.wrap-lss을 만들어 감싸고, 원래 위치에 추가해준다.
     */
    make_wrap(){
        this.$lss = document.querySelector(this.selector);
        const $before = this.$lss.nextElementSibling;
        this.$wrap = document.createElement('DIV');
        this.$wrap.classList.add('wrap-lss');
        this.$wrap.appendChild(this.$lss);
        document.body.insertBefore(this.$wrap,$before);
    }//make_wrap
 
    /**
     * pager를 만들어서 추가한다
     */
    make_pager(){
        this.$pager = document.createElement('DIV');
        this.$pager.classList.add('lss-pager');
        const $frag = document.createDocumentFragment();
        this.COUNT = this.$lss.childElementCount;
        this.$pager.style.setProperty('--wid-btn',`${100 / this.COUNT}%`)
        for(let i=0; i<this.COUNT; i++){
            const $btn = document.createElement('BUTTON');
            $btn.dataset.idx = i;
            $btn.title = `${i+1}번째 슬라이드`;
            if(i==0) $btn.classList.add('on');
            $frag.appendChild($btn);
        }//for
 
        this.$pager.appendChild($frag);
        this.$wrap.appendChild(this.$pager);
    }//make_pager
 
    /**
     * btns를 만들어서 추가한다
     */
    make_btns(){
        const $prev = document.createElement('BUTTON');
        const $next = document.createElement('BUTTON');
 
        $prev.classList.add('lss-btn-prev');
        $next.classList.add('lss-btn-next');
        
        this.$btns.push($prev);
        this.$btns.push($next);
 
        this.$btns.forEach($btn => this.$wrap.appendChild($btn));
    }//make_btns
 
    
    /**
     * 슬라이드의 첫번째와 마지막 아이템을 추가한다
     */
    add_copy_item_first_last(){
        const $first = this.$lss.children[0].cloneNode(true);
        const $last = this.$lss.children[this.$lss.childElementCount - 1].cloneNode(true);
 
        this.$lss.appendChild($first);
        this.$lss.insertBefore($last,this.$lss.children[0]);
    }//add_copy_item_first_last
 
    /** 
     * 슬라이드의 가로 사이즈 재설정 
     * */
    set_wid_slider = ()=>{
        this.widSlider = this.$wrap.offsetWidth;
        this.move_slider();
    }//set_wid_slider
 
    /** 
     * 슬라이드의 트랜지션을 끈다 
     * */
    off_transition(){
        this.$lss.classList.add('off');
    }//off_transition
 
    /** 슬라이드의 트랜지션을 킨다. */
    on_transition(){
        setTimeout(()=>{
            this.$lss.classList.remove('off');
        },100);
    }//on_transition
 
    /**
     * 슬라이드를 이동시킨다.
     */
    move_slider(){
        const amount = this.widSlider * (this.IDX + 1* -1;
        this.$lss.style.transform = `translateX(${amount}px)`;
 
        this.$lss.addEventListener('transitionend',()=>{
            //인덱스 확인
            if(this.IDX < 0 || this.IDX >= this.COUNT){
                if(this.IDX < 0this.IDX = this.COUNT - 1;
                if(this.IDX >= this.COUNT) this.IDX = 0;
                this.off_transition();
                this.move_slider();
            }//if
        },{once:true});
 
        if(this.$lss.classList.contains('off')) this.on_transition();
        this.toggle_pager_button();
    }//move_slider
 
    /**
     * 버튼 이벤트 추가
     */
    add_btn_event(){
        const [$prev,$next] = this.$btns;
        //이전 버튼
        $prev.addEventListener('click',()=>{
            --this.IDX;
            this.move_slider();
        });
 
        //다음 버튼
        $next.addEventListener('click',()=>{
            ++this.IDX;
            this.move_slider();
        });
    }//add_btn_event
 
    /**
     * 페이저 이벤트 추가
     */
    add_pager_event(){
        this.$pager.addEventListener('click',(e)=>{
            const $btn = e.target;
            if($btn.tagName != "BUTTON"return;
            const idx = parseInt($btn?.dataset?.idx);
            if(typeof idx !== "number"return;
            this.IDX = idx;
            this.move_slider();
        });
    }//add_pager_event
 
    /** 
     * pager의 .on이 붙을 버튼을 가져옴 
     * @returns {DOM} $btnOn
    */
    get_btn_on(){
        return this.$pager.children[this.IDX];
    }//get_btn_on
 
    /** pager의 button에 .on을 떼고 붙이고 */
    toggle_pager_button(){
        if(!this.isPager) return;
        const $$btn = this.$pager.children;
        const $btnOn = $$btn[this.IDX];
        Array.prototype.forEach.call($$btn,$btn=>{
            $btn.classList.toggle('on',$btn == $btnOn);
        });
    }//toggle_pager_button
 
    /**
     * 마우스 이벤트, 터치 이벤트 추가
     */
    add_mouse_touch_event(){
        this.$lss.addEventListener('mousedown',this.on_mouse_down,{once:true});
        this.$lss.addEventListener('touchstart',this.on_mouse_down,{once:true});
    }//add_mouse_touch_event
 
    /** 마우스다운, 터치스타트 시 */
    on_mouse_down = (e) =>{
        this.POS.prev = e.type == "mousedown" ? e.clientX : e.touches[0].clientX;
        this.$lss.addEventListener('mouseup',this.on_mouse_up, {once:true});
        this.$lss.addEventListener('touchend',this.on_mouse_up, {once:true});
    }//on_mouse_down
 
    /** 마우스업, 터치엔드 시 */
    on_mouse_up = (e) =>{
        this.POS.curr = e.type == "mouseup" ? e.clientX : e.changedTouches[0].clientX;
        const {prev,curr} = this.POS;
        const amount = Math.abs(prev - curr);
        if(amount >= 100){
            this.IDX += prev > curr ? 1 : (prev < curr ? -1 : 0); 
            this.move_slider();
        }
        this.add_mouse_touch_event();
    }//on_mouse_up
}//LikeSlickSlider
 
 
/* ================= */
const LSS = new LssBuilder()
.set_selector('#test')
.is_pager(true)
.is_btns(true)
.init();
 
LSS.init();
cs