forked from NickPiscitelli/Glider.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
glider.js
534 lines (438 loc) · 13.5 KB
/
glider.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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
/* @preserve
_____ __ _ __ _
/ ___// /(_)___/ /___ ____ (_)___
/ (_ // // // _ // -_)/ __/_ / /(_-<
\___//_//_/ \_,_/ \__//_/ (_)__/ //___/
|___/
Version: 1.6.4
Author: Nick Piscitelli (pickykneee)
Website: https://nickpiscitelli.com
Documentation: http://nickpiscitelli.github.io/Glider.js
License: MIT License
Release Date: October 25th, 2018
*/
/* global define */
(function (factory) {
typeof define === 'function' && define.amd
? define(factory)
: typeof exports === 'object'
? (module.exports = factory())
: factory()
})(function () {
/* globals window:true */
window = typeof window !== 'undefined' ? window : this;
('use strict') // eslint-disable-line no-unused-expressions
var Glider = (window.Glider = function (element, settings) {
var _ = this
if (element._glider) return element._glider
_.ele = element
_.ele.classList.add('glider')
// expose glider object to its DOM element
_.ele._glider = _
// merge user setting with defaults
_.opt = Object.assign(
{},
{
slidesToScroll: 1,
slidesToShow: 1,
resizeLock: true,
duration: 0.5,
// easeInQuad
easing: function (x, t, b, c, d) {
return c * (t /= d) * t + b
},
addTrack: true
},
settings
)
// set defaults
_.animate_id = _.page = _.slide = 0
_.arrows = {}
// preserve original options to
// extend breakpoint settings
_._opt = _.opt
if (_.opt.addTrack) {
// create track and wrap slides
_.track = document.createElement('div')
_.ele.appendChild(_.track)
while (_.ele.children.length !== 1) {
_.track.appendChild(_.ele.children[0])
}
} else {
// first and only child is the track
_.track = _.ele.children[0]
}
_.track.classList.add('glider-track')
// start glider
_.init()
// set events
_.resize = _.init.bind(_, true)
_.event(_.ele, 'add', {
scroll: _.updateControls.bind(_)
})
_.event(window, 'add', {
resize: _.resize
})
})
var gliderPrototype = Glider.prototype
gliderPrototype.init = function (refresh, paging) {
var _ = this
var width = 0
var height = 0
_.slides = _.track.children;
[].forEach.call(_.slides, function (_) {
_.classList.add('glider-slide')
})
_.containerWidth = _.ele.clientWidth
var breakpointChanged = _.settingsBreakpoint()
if (!paging) paging = breakpointChanged
if (_.opt.slidesToShow === 'auto' || _.opt._autoSlide) {
var slideCount = _.containerWidth / _.opt.itemWidth
_.opt._autoSlide = _.opt.slidesToShow = _.opt.exactWidth
? slideCount
: Math.floor(slideCount)
}
if (_.opt.slidesToScroll === 'auto') {
_.opt.slidesToScroll = Math.floor(_.opt.slidesToShow)
}
_.itemWidth = _.opt.exactWidth
? _.opt.itemWidth
: _.containerWidth / _.opt.slidesToShow;
// set slide dimensions
[].forEach.call(_.slides, function (__) {
__.style.height = 'auto'
__.style.width = _.itemWidth + 'px'
width += _.itemWidth
height = Math.max(__.offsetHeight, height)
})
_.track.style.width = width + 'px'
_.trackWidth = width
_.opt.resizeLock && _.scrollTo(_.slide * _.itemWidth, 0)
if (breakpointChanged || paging) {
_.bindArrows()
_.buildDots()
_.bindDrag()
}
_.updateControls()
_.emit(refresh ? 'refresh ' : 'loaded')
}
gliderPrototype.bindDrag = function () {
var _ = this
_.mouse = _.mouse || _.handleMouse.bind(_)
var mouseup = function () {
_.mouseDown = undefined
_.ele.classList.remove('drag')
}
var events = {
mouseup: mouseup,
mouseleave: mouseup,
mousedown: function (e) {
_.mouseDown = e.clientX
_.ele.classList.add('drag')
},
mousemove: _.mouse
}
_.ele.classList.toggle('draggable', _.opt.draggable === true)
_.event(_.ele, 'remove', events)
if (_.opt.draggable) _.event(_.ele, 'add', events)
}
gliderPrototype.buildDots = function () {
var _ = this
if (!_.opt.dots) {
if (_.dots) _.dots.innerHTML = ''
return
}
if (typeof _.opt.dots === 'string') {
_.dots = document.querySelector(_.opt.dots)
} else _.dots = _.opt.dots
if (!_.dots) return
_.dots.innerHTML = ''
_.dots.className = 'glider-dots'
for (var i = 0; i < Math.ceil(_.slides.length / _.opt.slidesToShow); ++i) {
var dot = document.createElement('button')
dot.dataset.index = i
dot.setAttribute('aria-label', 'Page ' + (i + 1))
dot.className = 'glider-dot ' + (i ? '' : 'active')
_.event(dot, 'add', {
click: _.scrollItem.bind(_, i, true)
})
_.dots.appendChild(dot)
}
}
gliderPrototype.bindArrows = function () {
var _ = this
if (!_.opt.arrows) {
Object.keys(_.arrows).forEach(function (direction) {
var element = _.arrows[direction]
_.event(element, 'remove', { click: element._func })
})
return
}
['prev', 'next'].forEach(function (direction) {
var arrow = _.opt.arrows[direction]
if (arrow) {
if (typeof arrow === 'string') arrow = document.querySelector(arrow)
arrow._func = arrow._func || _.scrollItem.bind(_, direction)
_.event(arrow, 'remove', {
click: arrow._func
})
_.event(arrow, 'add', {
click: arrow._func
})
_.arrows[direction] = arrow
}
})
}
gliderPrototype.updateControls = function (event) {
var _ = this
if (event && !_.opt.scrollPropagate) {
event.stopPropagation()
}
var disableArrows = _.containerWidth >= _.trackWidth
if (!_.opt.rewind) {
if (_.arrows.prev) {
_.arrows.prev.classList.toggle(
'disabled',
_.ele.scrollLeft <= 0 || disableArrows
)
}
if (_.arrows.next) {
_.arrows.next.classList.toggle(
'disabled',
_.ele.scrollLeft + _.containerWidth >= Math.floor(_.trackWidth) ||
disableArrows
)
}
}
_.slide = Math.round(_.ele.scrollLeft / _.itemWidth)
_.page = Math.round(_.ele.scrollLeft / _.containerWidth)
var middle = _.slide + Math.floor(Math.floor(_.opt.slidesToShow) / 2)
var extraMiddle = Math.floor(_.opt.slidesToShow) % 2 ? 0 : middle + 1
if (Math.floor(_.opt.slidesToShow) === 1) {
extraMiddle = 0
}
// the last page may be less than one half of a normal page width so
// the page is rounded down. when at the end, force the page to turn
if (_.ele.scrollLeft + _.containerWidth >= Math.floor(_.trackWidth)) {
_.page = _.dots ? _.dots.children.length - 1 : 0
}
[].forEach.call(_.slides, function (slide, index) {
var slideClasses = slide.classList
var wasVisible = slideClasses.contains('visible')
var start = _.ele.scrollLeft
var end = _.ele.scrollLeft + _.containerWidth
var itemStart = _.itemWidth * index
var itemEnd = itemStart + _.itemWidth;
[].forEach.call(slideClasses, function (className) {
/^left|right/.test(className) && slideClasses.remove(className)
})
slideClasses.toggle('active', _.slide === index)
if (middle === index || (extraMiddle && extraMiddle === index)) {
slideClasses.add('center')
} else {
slideClasses.remove('center')
slideClasses.add(
[
index < middle ? 'left' : 'right',
Math.abs(index - (index < middle ? middle : extraMiddle || middle))
].join('-')
)
}
var isVisible = itemStart >= start && itemEnd <= end
slideClasses.toggle('visible', isVisible)
if (isVisible !== wasVisible) {
_.emit('slide-' + (isVisible ? 'visible' : 'hidden'), {
slide: index
})
}
})
if (_.dots) {
[].forEach.call(_.dots.children, function (dot, index) {
dot.classList.toggle('active', _.page === index)
})
}
if (event && _.opt.scrollLock) {
clearTimeout(_.scrollLock)
_.scrollLock = setTimeout(function () {
clearTimeout(_.scrollLock)
if ((_.ele.scrollLeft / _.itemWidth) % 1) {
_.scrollItem(_.round(_.ele.scrollLeft / _.itemWidth))
}
}, _.opt.scrollLockDelay || 250)
}
}
gliderPrototype.scrollItem = function (slide, dot, e) {
if (e) e.preventDefault()
var _ = this
var originalSlide = slide
++_.animate_id
if (dot === true) {
slide = slide * _.containerWidth
slide = Math.round(slide / _.itemWidth) * _.itemWidth
} else {
if (typeof slide === 'string') {
var backwards = slide === 'prev'
// use precise location if fractional slides are on
if (_.opt.slidesToScroll % 1 || _.opt.slidesToShow % 1) {
slide = _.round(_.ele.scrollLeft / _.itemWidth)
} else {
slide = _.slide
}
if (backwards) slide -= _.opt.slidesToScroll
else slide += _.opt.slidesToScroll
if (_.opt.rewind) {
var scrollLeft = _.ele.scrollLeft
slide =
backwards && !scrollLeft
? _.slides.length
: !backwards &&
scrollLeft + _.containerWidth >= Math.floor(_.trackWidth)
? 0
: slide
}
}
slide = Math.max(Math.min(slide, _.slides.length), 0)
_.slide = slide
slide = _.itemWidth * slide
}
_.scrollTo(
slide,
_.opt.duration * Math.abs(_.ele.scrollLeft - slide),
function () {
_.updateControls()
_.emit('animated', {
value: originalSlide,
type:
typeof originalSlide === 'string' ? 'arrow' : dot ? 'dot' : 'slide'
})
}
)
return false
}
gliderPrototype.settingsBreakpoint = function () {
var _ = this
var resp = _._opt.responsive
if (resp) {
// Sort the breakpoints in mobile first order
resp.sort(function (a, b) {
return b.breakpoint - a.breakpoint
})
for (var i = 0; i < resp.length; ++i) {
var size = resp[i]
if (window.innerWidth >= size.breakpoint) {
if (_.breakpoint !== size.breakpoint) {
_.opt = Object.assign({}, _._opt, size.settings)
_.breakpoint = size.breakpoint
return true
}
return false
}
}
}
// set back to defaults in case they were overriden
var breakpointChanged = _.breakpoint !== 0
_.opt = Object.assign({}, _._opt)
_.breakpoint = 0
return breakpointChanged
}
gliderPrototype.scrollTo = function (scrollTarget, scrollDuration, callback) {
var _ = this
var start = new Date().getTime()
var animateIndex = _.animate_id
var animate = function () {
var now = new Date().getTime() - start
_.ele.scrollLeft =
_.ele.scrollLeft +
(scrollTarget - _.ele.scrollLeft) *
_.opt.easing(0, now, 0, 1, scrollDuration)
if (now < scrollDuration && animateIndex === _.animate_id) {
window.requestAnimationFrame(animate)
} else {
_.ele.scrollLeft = scrollTarget
callback && callback.call(_)
}
}
window.requestAnimationFrame(animate)
}
gliderPrototype.removeItem = function (index) {
var _ = this
if (_.slides.length) {
_.track.removeChild(_.slides[index])
_.refresh(true)
_.emit('remove')
}
}
gliderPrototype.addItem = function (ele) {
var _ = this
_.track.appendChild(ele)
_.refresh(true)
_.emit('add')
}
gliderPrototype.handleMouse = function (e) {
var _ = this
if (_.mouseDown) {
_.ele.scrollLeft +=
(_.mouseDown - e.clientX) * (_.opt.dragVelocity || 3.3)
_.mouseDown = e.clientX
}
}
// used to round to the nearest 0.XX fraction
gliderPrototype.round = function (double) {
var _ = this
var step = _.opt.slidesToScroll % 1 || 1
var inv = 1.0 / step
return Math.round(double * inv) / inv
}
gliderPrototype.refresh = function (paging) {
var _ = this
_.init(true, paging)
}
gliderPrototype.setOption = function (opt, global) {
var _ = this
if (_.breakpoint && !global) {
_._opt.responsive.forEach(function (v) {
if (v.breakpoint === _.breakpoint) {
v.settings = Object.assign({}, v.settings, opt)
}
})
} else {
_._opt = Object.assign({}, _._opt, opt)
}
_.breakpoint = 0
_.settingsBreakpoint()
}
gliderPrototype.destroy = function () {
var _ = this
var replace = _.ele.cloneNode(true)
var clear = function (ele) {
ele.removeAttribute('style');
[].forEach.call(ele.classList, function (className) {
/^glider/.test(className) && ele.classList.remove(className)
})
}
// remove track
replace.children[0].outerHTML = replace.children[0].innerHTML
clear(replace);
[].forEach.call(replace.getElementsByTagName('*'), clear)
_.ele.parentNode.replaceChild(replace, _.ele)
_.event(window, 'remove', {
resize: _.resize
})
_.emit('destroy')
}
gliderPrototype.emit = function (name, arg) {
var _ = this
var e = new window.CustomEvent('glider-' + name, {
bubbles: !_.opt.eventPropagate,
detail: arg
})
_.ele.dispatchEvent(e)
}
gliderPrototype.event = function (ele, type, args) {
var eventHandler = ele[type + 'EventListener'].bind(ele)
Object.keys(args).forEach(function (k) {
eventHandler(k, args[k])
})
}
return Glider
})