-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathcarousel.js
702 lines (614 loc) · 20.6 KB
/
carousel.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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
(function ($) {
'use strict';
let _defaults = {
duration: 200, // ms
dist: -100, // zoom scale TODO: make this more intuitive as an option
shift: 0, // spacing for center image
padding: 0, // Padding between non center items
fullWidth: false, // Change to full width styles
indicators: false, // Toggle indicators
noWrap: false, // Don't wrap around and cycle through items.
onCycleTo: null // Callback for when a new slide is cycled to.
};
/**
* @class
*
*/
class Carousel {
/**
* Construct Carousel instance
* @constructor
* @param {Element} el
* @param {Object} options
*/
constructor(el, options) {
// If exists, destroy and reinitialize
if (!!el.M_Carousel) {
el.M_Carousel.destroy();
}
this.el = el;
this.$el = $(el);
this.el.M_Carousel = this;
/**
* Options for the carousel
* @member Carousel#options
* @prop {Number} duration
* @prop {Number} dist
* @prop {number} shift
* @prop {number} padding
* @prop {Boolean} fullWidth
* @prop {Boolean} indicators
* @prop {Boolean} noWrap
* @prop {Function} onCycleTo
*/
this.options = $.extend({}, Carousel.defaults, options);
// Setup
this.hasMultipleSlides = this.$el.find('.carousel-item').length > 1;
this.showIndicators = this.options.indicators && this.hasMultipleSlides;
this.noWrap = this.options.noWrap || !this.hasMultipleSlides;
this.pressed = false;
this.dragged = false;
this.offset = this.target = 0;
this.images = [];
this.itemWidth = this.$el.find('.carousel-item').first().innerWidth();
this.itemHeight = this.$el.find('.carousel-item').first().innerHeight();
this.dim = this.itemWidth * 2 + this.options.padding || 1; // Make sure dim is non zero for divisions.
this._autoScrollBound = this._autoScroll.bind(this);
this._trackBound = this._track.bind(this);
// Full Width carousel setup
if (this.options.fullWidth) {
this.options.dist = 0;
this._setCarouselHeight();
// Offset fixed items when indicators.
if (this.showIndicators) {
this.$el.find('.carousel-fixed-item').addClass('with-indicators');
}
}
// Iterate through slides
this.$indicators = $('<ul class="indicators"></ul>');
this.$el.find('.carousel-item').each((el, i) => {
this.images.push(el);
if (this.showIndicators) {
let $indicator = $('<li class="indicator-item"></li>');
// Add active to first by default.
if (i === 0) {
$indicator[0].classList.add('active');
}
this.$indicators.append($indicator);
}
});
if (this.showIndicators) {
this.$el.append(this.$indicators);
}
this.count = this.images.length;
// Setup cross browser string
this.xform = 'transform';
['webkit', 'Moz', 'O', 'ms'].every((prefix) => {
var e = prefix + 'Transform';
if (typeof document.body.style[e] !== 'undefined') {
this.xform = e;
return false;
}
return true;
});
this._setupEventHandlers();
this._scroll(this.offset);
}
static get defaults() {
return _defaults;
}
static init($els, options) {
let arr = [];
$els.each(function() {
arr.push(new Carousel(this, options));
});
return arr;
}
/**
* Get Instance
*/
static getInstance(el) {
let domElem = !!el.jquery ? el[0] : el;
return domElem.M_Carousel;
}
/**
* Teardown component
*/
destroy() {
this._removeEventHandlers();
this.el.M_Carousel = undefined;
}
/**
* Setup Event Handlers
*/
_setupEventHandlers() {
this._handleCarouselTapBound = this._handleCarouselTap.bind(this);
this._handleCarouselDragBound = this._handleCarouselDrag.bind(this);
this._handleCarouselReleaseBound = this._handleCarouselRelease.bind(this);
this._handleCarouselClickBound = this._handleCarouselClick.bind(this);
if (typeof window.ontouchstart !== 'undefined') {
this.el.addEventListener('touchstart', this._handleCarouselTapBound);
this.el.addEventListener('touchmove', this._handleCarouselDragBound);
this.el.addEventListener('touchend', this._handleCarouselReleaseBound);
}
this.el.addEventListener('mousedown', this._handleCarouselTapBound);
this.el.addEventListener('mousemove', this._handleCarouselDragBound);
this.el.addEventListener('mouseup', this._handleCarouselReleaseBound);
this.el.addEventListener('mouseleave', this._handleCarouselReleaseBound);
this.el.addEventListener('click', this._handleCarouselClickBound);
if (this.showIndicators && this.$indicators) {
this._handleIndicatorClickBound = this._handleIndicatorClick.bind(this);
this.$indicators.find('.indicator-item').each((el, i) => {
el.addEventListener('click', this._handleIndicatorClickBound);
});
}
// Resize
let throttledResize = M.throttle(this._handleResize, 200);
this._handleThrottledResizeBound = throttledResize.bind(this);
window.addEventListener('resize', this._handleThrottledResizeBound);
}
/**
* Remove Event Handlers
*/
_removeEventHandlers() {
if (typeof window.ontouchstart !== 'undefined') {
this.el.removeEventListener('touchstart', this._handleCarouselTapBound);
this.el.removeEventListener('touchmove', this._handleCarouselDragBound);
this.el.removeEventListener('touchend', this._handleCarouselReleaseBound);
}
this.el.removeEventListener('mousedown', this._handleCarouselTapBound);
this.el.removeEventListener('mousemove', this._handleCarouselDragBound);
this.el.removeEventListener('mouseup', this._handleCarouselReleaseBound);
this.el.removeEventListener('mouseleave', this._handleCarouselReleaseBound);
this.el.removeEventListener('click', this._handleCarouselClickBound);
if (this.showIndicators && this.$indicators) {
this.$indicators.find('.indicator-item').each((el, i) => {
el.removeEventListener('click', this._handleIndicatorClickBound);
});
}
window.removeEventListener('resize', this._handleThrottledResizeBound);
}
/**
* Handle Carousel Tap
* @param {Event} e
*/
_handleCarouselTap(e) {
// Fixes firefox draggable image bug
if (e.type === 'mousedown' && $(e.target).is('img')) {
e.preventDefault();
}
this.pressed = true;
this.dragged = false;
this.verticalDragged = false;
this.reference = this._xpos(e);
this.referenceY = this._ypos(e);
this.velocity = this.amplitude = 0;
this.frame = this.offset;
this.timestamp = Date.now();
clearInterval(this.ticker);
this.ticker = setInterval(this._trackBound, 100);
}
/**
* Handle Carousel Drag
* @param {Event} e
*/
_handleCarouselDrag(e) {
let x, y, delta, deltaY;
if (this.pressed) {
x = this._xpos(e);
y = this._ypos(e);
delta = this.reference - x;
deltaY = Math.abs(this.referenceY - y);
if (deltaY < 30 && !this.verticalDragged) {
// If vertical scrolling don't allow dragging.
if (delta > 2 || delta < -2) {
this.dragged = true;
this.reference = x;
this._scroll(this.offset + delta);
}
} else if (this.dragged) {
// If dragging don't allow vertical scroll.
e.preventDefault();
e.stopPropagation();
return false;
} else {
// Vertical scrolling.
this.verticalDragged = true;
}
}
if (this.dragged) {
// If dragging don't allow vertical scroll.
e.preventDefault();
e.stopPropagation();
return false;
}
}
/**
* Handle Carousel Release
* @param {Event} e
*/
_handleCarouselRelease(e) {
if (this.pressed) {
this.pressed = false;
} else {
return;
}
clearInterval(this.ticker);
this.target = this.offset;
if (this.velocity > 10 || this.velocity < -10) {
this.amplitude = 0.9 * this.velocity;
this.target = this.offset + this.amplitude;
}
this.target = Math.round(this.target / this.dim) * this.dim;
// No wrap of items.
if (this.noWrap) {
if (this.target >= this.dim * (this.count - 1)) {
this.target = this.dim * (this.count - 1);
} else if (this.target < 0) {
this.target = 0;
}
}
this.amplitude = this.target - this.offset;
this.timestamp = Date.now();
requestAnimationFrame(this._autoScrollBound);
if (this.dragged) {
e.preventDefault();
e.stopPropagation();
}
return false;
}
/**
* Handle Carousel CLick
* @param {Event} e
*/
_handleCarouselClick(e) {
// Disable clicks if carousel was dragged.
if (this.dragged) {
e.preventDefault();
e.stopPropagation();
return false;
} else if (!this.options.fullWidth) {
let clickedIndex = $(e.target).closest('.carousel-item').index();
let diff = this._wrap(this.center) - clickedIndex;
// Disable clicks if carousel was shifted by click
if (diff !== 0) {
e.preventDefault();
e.stopPropagation();
}
this._cycleTo(clickedIndex);
}
}
/**
* Handle Indicator CLick
* @param {Event} e
*/
_handleIndicatorClick(e) {
e.stopPropagation();
let indicator = $(e.target).closest('.indicator-item');
if (indicator.length) {
this._cycleTo(indicator.index());
}
}
/**
* Handle Throttle Resize
* @param {Event} e
*/
_handleResize(e) {
if (this.options.fullWidth) {
this.itemWidth = this.$el.find('.carousel-item').first().innerWidth();
this.imageHeight = this.$el.find('.carousel-item.active').height();
this.dim = this.itemWidth * 2 + this.options.padding;
this.offset = this.center * 2 * this.itemWidth;
this.target = this.offset;
this._setCarouselHeight(true);
} else {
this._scroll();
}
}
/**
* Set carousel height based on first slide
* @param {Booleam} imageOnly - true for image slides
*/
_setCarouselHeight(imageOnly) {
let firstSlide = this.$el.find('.carousel-item.active').length ? this.$el.find('.carousel-item.active').first() : this.$el.find('.carousel-item').first();
let firstImage = firstSlide.find('img').first();
if (firstImage.length) {
if (firstImage[0].complete) {
// If image won't trigger the load event
let imageHeight = firstImage.height();
if (imageHeight > 0) {
this.$el.css('height', imageHeight + 'px');
} else {
// If image still has no height, use the natural dimensions to calculate
let naturalWidth = firstImage[0].naturalWidth;
let naturalHeight = firstImage[0].naturalHeight;
let adjustedHeight = (this.$el.width() / naturalWidth) * naturalHeight;
this.$el.css('height', adjustedHeight + 'px');
}
} else {
// Get height when image is loaded normally
firstImage.one('load', (el, i) => {
this.$el.css('height', el.offsetHeight + 'px');
});
}
} else if (!imageOnly) {
let slideHeight = firstSlide.height();
this.$el.css('height', slideHeight + 'px');
}
}
/**
* Get x position from event
* @param {Event} e
*/
_xpos(e) {
// touch event
if (e.targetTouches && (e.targetTouches.length >= 1)) {
return e.targetTouches[0].clientX;
}
// mouse event
return e.clientX;
}
/**
* Get y position from event
* @param {Event} e
*/
_ypos(e) {
// touch event
if (e.targetTouches && (e.targetTouches.length >= 1)) {
return e.targetTouches[0].clientY;
}
// mouse event
return e.clientY;
}
/**
* Wrap index
* @param {Number} x
*/
_wrap(x) {
return (x >= this.count) ? (x % this.count) : (x < 0) ? this._wrap(this.count + (x % this.count)) : x;
}
/**
* Tracks scrolling information
*/
_track() {
let now, elapsed, delta, v;
now = Date.now();
elapsed = now - this.timestamp;
this.timestamp = now;
delta = this.offset - this.frame;
this.frame = this.offset;
v = 1000 * delta / (1 + elapsed);
this.velocity = 0.8 * v + 0.2 * this.velocity;
}
/**
* Auto scrolls to nearest carousel item.
*/
_autoScroll() {
let elapsed, delta;
if (this.amplitude) {
elapsed = Date.now() - this.timestamp;
delta = this.amplitude * Math.exp(-elapsed / this.options.duration);
if (delta > 2 || delta < -2) {
this._scroll(this.target - delta);
requestAnimationFrame(this._autoScrollBound);
} else {
this._scroll(this.target);
}
}
}
/**
* Scroll to target
* @param {Number} x
*/
_scroll(x) {
// Track scrolling state
if (!this.$el.hasClass('scrolling')) {
this.el.classList.add('scrolling');
}
if (this.scrollingTimeout != null) {
window.clearTimeout(this.scrollingTimeout);
}
this.scrollingTimeout = window.setTimeout(() => {
this.$el.removeClass('scrolling');
}, this.options.duration);
// Start actual scroll
let i, half, delta, dir, tween, el, alignment, zTranslation, tweenedOpacity;
let lastCenter = this.center;
this.offset = (typeof x === 'number') ? x : this.offset;
this.center = Math.floor((this.offset + this.dim / 2) / this.dim);
delta = this.offset - this.center * this.dim;
dir = (delta < 0) ? 1 : -1;
tween = -dir * delta * 2 / this.dim;
half = this.count >> 1;
if (!this.options.fullWidth) {
alignment = 'translateX(' + (this.el.clientWidth - this.itemWidth) / 2 + 'px) ';
alignment += 'translateY(' + (this.el.clientHeight - this.itemHeight) / 2 + 'px)';
} else {
alignment = 'translateX(0)';
}
// Set indicator active
if (this.showIndicators) {
let diff = (this.center % this.count);
let activeIndicator = this.$indicators.find('.indicator-item.active');
if (activeIndicator.index() !== diff) {
activeIndicator.removeClass('active');
this.$indicators.find('.indicator-item').eq(diff)[0].classList.add('active');
}
}
// center
// Don't show wrapped items.
if (!this.noWrap || (this.center >= 0 && this.center < this.count)) {
el = this.images[this._wrap(this.center)];
// Add active class to center item.
if (!$(el).hasClass('active')) {
this.$el.find('.carousel-item').removeClass('active');
el.classList.add('active');
}
el.style[this.xform] = alignment +
' translateX(' + (-delta / 2) + 'px)' +
' translateX(' + (dir * this.options.shift * tween * i) + 'px)' +
' translateZ(' + (this.options.dist * tween) + 'px)';
el.style.zIndex = 0;
if (this.options.fullWidth) { tweenedOpacity = 1; }
else { tweenedOpacity = 1 - 0.2 * tween; }
el.style.opacity = tweenedOpacity;
el.style.visibility = 'visible';
}
for (i = 1; i <= half; ++i) {
// right side
if (this.options.fullWidth) {
zTranslation = this.options.dist;
tweenedOpacity = (i === half && delta < 0) ? 1 - tween : 1;
} else {
zTranslation = this.options.dist * (i * 2 + tween * dir);
tweenedOpacity = 1 - 0.2 * (i * 2 + tween * dir);
}
// Don't show wrapped items.
if (!this.noWrap || this.center + i < this.count) {
el = this.images[this._wrap(this.center + i)];
el.style[this.xform] = alignment +
' translateX(' + (this.options.shift + (this.dim * i - delta) / 2) + 'px)' +
' translateZ(' + zTranslation + 'px)';
el.style.zIndex = -i;
el.style.opacity = tweenedOpacity;
el.style.visibility = 'visible';
}
// left side
if (this.options.fullWidth) {
zTranslation = this.options.dist;
tweenedOpacity = (i === half && delta > 0) ? 1 - tween : 1;
} else {
zTranslation = this.options.dist * (i * 2 - tween * dir);
tweenedOpacity = 1 - 0.2 * (i * 2 - tween * dir);
}
// Don't show wrapped items.
if (!this.noWrap || this.center - i >= 0) {
el = this.images[this._wrap(this.center - i)];
el.style[this.xform] = alignment +
' translateX(' + (-this.options.shift + (-this.dim * i - delta) / 2) + 'px)' +
' translateZ(' + zTranslation + 'px)';
el.style.zIndex = -i;
el.style.opacity = tweenedOpacity;
el.style.visibility = 'visible';
}
}
// center
// Don't show wrapped items.
if (!this.noWrap || (this.center >= 0 && this.center < this.count)) {
el = this.images[this._wrap(this.center)];
el.style[this.xform] = alignment +
' translateX(' + (-delta / 2) + 'px)' +
' translateX(' + (dir * this.options.shift * tween) + 'px)' +
' translateZ(' + (this.options.dist * tween) + 'px)';
el.style.zIndex = 0;
if (this.options.fullWidth) { tweenedOpacity = 1; }
else { tweenedOpacity = 1 - 0.2 * tween; }
el.style.opacity = tweenedOpacity;
el.style.visibility = 'visible';
}
// onCycleTo callback
let $currItem = this.$el.find('.carousel-item').eq(this._wrap(this.center));
if (lastCenter !== this.center &&
typeof(this.options.onCycleTo) === "function") {
this.options.onCycleTo.call(this, $currItem[0], this.dragged);
}
// One time callback
if (typeof(this.oneTimeCallback) === "function") {
this.oneTimeCallback.call(this, $currItem[0], this.dragged);
this.oneTimeCallback = null;
}
}
/**
* Cycle to target
* @param {Number} n
* @param {Function} callback
*/
_cycleTo(n, callback) {
let diff = (this.center % this.count) - n;
// Account for wraparound.
if (!this.noWrap) {
if (diff < 0) {
if (Math.abs(diff + this.count) < Math.abs(diff)) { diff += this.count; }
} else if (diff > 0) {
if (Math.abs(diff - this.count) < diff) { diff -= this.count; }
}
}
this.target = (this.dim * Math.round(this.offset / this.dim));
// Next
if (diff < 0) {
this.target += (this.dim * Math.abs(diff));
// Prev
} else if (diff > 0) {
this.target -= (this.dim * diff);
}
// Set one time callback
if (typeof(callback) === "function") {
this.oneTimeCallback = callback;
}
// Scroll
if (this.offset !== this.target) {
this.amplitude = this.target - this.offset;
this.timestamp = Date.now();
requestAnimationFrame(this._autoScrollBound);
}
}
/**
* Cycle to next item
* @param {Number} [n]
*/
next(n) {
if (n === undefined || isNaN(n)) {
n = 1;
}
let index = this.center + n;
if (index > this.count || index < 0) {
if (this.noWrap) {
return;
} else {
index = this._wrap(index);
}
}
this._cycleTo(index);
}
/**
* Cycle to previous item
* @param {Number} [n]
*/
prev(n) {
if (n === undefined || isNaN(n)) {
n = 1;
}
let index = this.center - n;
if (index > this.count || index < 0) {
if (this.noWrap) {
return;
} else {
index = this._wrap(index);
}
}
this._cycleTo(index);
}
/**
* Cycle to nth item
* @param {Number} [n]
* @param {Function} callback
*/
set(n, callback) {
if (n === undefined || isNaN(n)) {
n = 0;
}
if (n > this.count || n < 0) {
if (this.noWrap) {
return;
} else {
n = this._wrap(n);
}
}
this._cycleTo(n, callback);
}
}
M.Carousel = Carousel;
if (M.jQueryLoaded) {
M.initializeJqueryWrapper(Carousel, 'carousel', 'M_Carousel');
}
}( cash ));