/
tiny-slider.js
3176 lines (2684 loc) · 97.5 KB
/
tiny-slider.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
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
var tns = (function (){
var win = window;
var raf = win.requestAnimationFrame
|| win.webkitRequestAnimationFrame
|| win.mozRequestAnimationFrame
|| win.msRequestAnimationFrame
|| function(cb) { return setTimeout(cb, 16); };
var win$1 = window;
var caf = win$1.cancelAnimationFrame
|| win$1.mozCancelAnimationFrame
|| function(id){ clearTimeout(id); };
function extend() {
var obj, name, copy,
target = arguments[0] || {},
i = 1,
length = arguments.length;
for (; i < length; i++) {
if ((obj = arguments[i]) !== null) {
for (name in obj) {
copy = obj[name];
if (target === copy) {
continue;
} else if (copy !== undefined) {
target[name] = copy;
}
}
}
}
return target;
}
function checkStorageValue (value) {
return ['true', 'false'].indexOf(value) >= 0 ? JSON.parse(value) : value;
}
function setLocalStorage(storage, key, value, access) {
if (access) {
try { storage.setItem(key, value); } catch (e) {}
}
return value;
}
function getSlideId() {
var id = window.tnsId;
window.tnsId = !id ? 1 : id + 1;
return 'tns' + window.tnsId;
}
function getBody () {
var doc = document,
body = doc.body;
if (!body) {
body = doc.createElement('body');
body.fake = true;
}
return body;
}
var docElement = document.documentElement;
function setFakeBody (body) {
var docOverflow = '';
if (body.fake) {
docOverflow = docElement.style.overflow;
//avoid crashing IE8, if background image is used
body.style.background = '';
//Safari 5.13/5.1.4 OSX stops loading if ::-webkit-scrollbar is used and scrollbars are visible
body.style.overflow = docElement.style.overflow = 'hidden';
docElement.appendChild(body);
}
return docOverflow;
}
function resetFakeBody (body, docOverflow) {
if (body.fake) {
body.remove();
docElement.style.overflow = docOverflow;
// Trigger layout so kinetic scrolling isn't disabled in iOS6+
// eslint-disable-next-line
docElement.offsetHeight;
}
}
// get css-calc
function calc() {
var doc = document,
body = getBody(),
docOverflow = setFakeBody(body),
div = doc.createElement('div'),
result = false;
body.appendChild(div);
try {
var str = '(10px * 10)',
vals = ['calc' + str, '-moz-calc' + str, '-webkit-calc' + str],
val;
for (var i = 0; i < 3; i++) {
val = vals[i];
div.style.width = val;
if (div.offsetWidth === 100) {
result = val.replace(str, '');
break;
}
}
} catch (e) {}
body.fake ? resetFakeBody(body, docOverflow) : div.remove();
return result;
}
// get subpixel support value
function percentageLayout() {
// check subpixel layout supporting
var doc = document,
body = getBody(),
docOverflow = setFakeBody(body),
wrapper = doc.createElement('div'),
outer = doc.createElement('div'),
str = '',
count = 70,
perPage = 3,
supported = false;
wrapper.className = "tns-t-subp2";
outer.className = "tns-t-ct";
for (var i = 0; i < count; i++) {
str += '<div></div>';
}
outer.innerHTML = str;
wrapper.appendChild(outer);
body.appendChild(wrapper);
supported = Math.abs(wrapper.getBoundingClientRect().left - outer.children[count - perPage].getBoundingClientRect().left) < 2;
body.fake ? resetFakeBody(body, docOverflow) : wrapper.remove();
return supported;
}
function mediaquerySupport () {
var doc = document,
body = getBody(),
docOverflow = setFakeBody(body),
div = doc.createElement('div'),
style = doc.createElement('style'),
rule = '@media all and (min-width:1px){.tns-mq-test{position:absolute}}',
position;
style.type = 'text/css';
div.className = 'tns-mq-test';
body.appendChild(style);
body.appendChild(div);
if (style.styleSheet) {
style.styleSheet.cssText = rule;
} else {
style.appendChild(doc.createTextNode(rule));
}
position = window.getComputedStyle ? window.getComputedStyle(div).position : div.currentStyle['position'];
body.fake ? resetFakeBody(body, docOverflow) : div.remove();
return position === "absolute";
}
// create and append style sheet
function createStyleSheet (media) {
// Create the <style> tag
var style = document.createElement("style");
// style.setAttribute("type", "text/css");
// Add a media (and/or media query) here if you'd like!
// style.setAttribute("media", "screen")
// style.setAttribute("media", "only screen and (max-width : 1024px)")
if (media) { style.setAttribute("media", media); }
// WebKit hack :(
// style.appendChild(document.createTextNode(""));
// Add the <style> element to the page
document.querySelector('head').appendChild(style);
return style.sheet ? style.sheet : style.styleSheet;
}
// cross browsers addRule method
function addCSSRule(sheet, selector, rules, index) {
// return raf(function() {
'insertRule' in sheet ?
sheet.insertRule(selector + '{' + rules + '}', index) :
sheet.addRule(selector, rules, index);
// });
}
// cross browsers addRule method
function removeCSSRule(sheet, index) {
// return raf(function() {
'deleteRule' in sheet ?
sheet.deleteRule(index) :
sheet.removeRule(index);
// });
}
function getCssRulesLength(sheet) {
var rule = ('insertRule' in sheet) ? sheet.cssRules : sheet.rules;
return rule.length;
}
function toDegree (y, x) {
return Math.atan2(y, x) * (180 / Math.PI);
}
function getTouchDirection(angle, range) {
var direction = false,
gap = Math.abs(90 - Math.abs(angle));
if (gap >= 90 - range) {
direction = 'horizontal';
} else if (gap <= range) {
direction = 'vertical';
}
return direction;
}
// https://toddmotto.com/ditch-the-array-foreach-call-nodelist-hack/
function forEach (arr, callback, scope) {
for (var i = 0, l = arr.length; i < l; i++) {
callback.call(scope, arr[i], i);
}
}
var classListSupport = 'classList' in document.createElement('_');
var hasClass = classListSupport ?
function (el, str) { return el.classList.contains(str); } :
function (el, str) { return el.className.indexOf(str) >= 0; };
var addClass = classListSupport ?
function (el, str) {
if (!hasClass(el, str)) { el.classList.add(str); }
} :
function (el, str) {
if (!hasClass(el, str)) { el.className += ' ' + str; }
};
var removeClass = classListSupport ?
function (el, str) {
if (hasClass(el, str)) { el.classList.remove(str); }
} :
function (el, str) {
if (hasClass(el, str)) { el.className = el.className.replace(str, ''); }
};
function hasAttr(el, attr) {
return el.hasAttribute(attr);
}
function getAttr(el, attr) {
return el.getAttribute(attr);
}
function isNodeList(el) {
// Only NodeList has the "item()" function
return typeof el.item !== "undefined";
}
function setAttrs(els, attrs) {
els = (isNodeList(els) || els instanceof Array) ? els : [els];
if (Object.prototype.toString.call(attrs) !== '[object Object]') { return; }
for (var i = els.length; i--;) {
for(var key in attrs) {
els[i].setAttribute(key, attrs[key]);
}
}
}
function removeAttrs(els, attrs) {
els = (isNodeList(els) || els instanceof Array) ? els : [els];
attrs = (attrs instanceof Array) ? attrs : [attrs];
var attrLength = attrs.length;
for (var i = els.length; i--;) {
for (var j = attrLength; j--;) {
els[i].removeAttribute(attrs[j]);
}
}
}
function arrayFromNodeList (nl) {
var arr = [];
for (var i = 0, l = nl.length; i < l; i++) {
arr.push(nl[i]);
}
return arr;
}
function hideElement(el, forceHide) {
if (el.style.display !== 'none') { el.style.display = 'none'; }
}
function showElement(el, forceHide) {
if (el.style.display === 'none') { el.style.display = ''; }
}
function isVisible(el) {
return window.getComputedStyle(el).display !== 'none';
}
function whichProperty(props){
if (typeof props === 'string') {
var arr = [props],
Props = props.charAt(0).toUpperCase() + props.substr(1),
prefixes = ['Webkit', 'Moz', 'ms', 'O'];
prefixes.forEach(function(prefix) {
if (prefix !== 'ms' || props === 'transform') {
arr.push(prefix + Props);
}
});
props = arr;
}
var el = document.createElement('fakeelement'),
len = props.length;
for(var i = 0; i < props.length; i++){
var prop = props[i];
if( el.style[prop] !== undefined ){ return prop; }
}
return false; // explicit for ie9-
}
function has3DTransforms(tf){
if (!tf) { return false; }
if (!window.getComputedStyle) { return false; }
var doc = document,
body = getBody(),
docOverflow = setFakeBody(body),
el = doc.createElement('p'),
has3d,
cssTF = tf.length > 9 ? '-' + tf.slice(0, -9).toLowerCase() + '-' : '';
cssTF += 'transform';
// Add it to the body to get the computed style
body.insertBefore(el, null);
el.style[tf] = 'translate3d(1px,1px,1px)';
has3d = window.getComputedStyle(el).getPropertyValue(cssTF);
body.fake ? resetFakeBody(body, docOverflow) : el.remove();
return (has3d !== undefined && has3d.length > 0 && has3d !== "none");
}
// get transitionend, animationend based on transitionDuration
// @propin: string
// @propOut: string, first-letter uppercase
// Usage: getEndProperty('WebkitTransitionDuration', 'Transition') => webkitTransitionEnd
function getEndProperty(propIn, propOut) {
var endProp = false;
if (/^Webkit/.test(propIn)) {
endProp = 'webkit' + propOut + 'End';
} else if (/^O/.test(propIn)) {
endProp = 'o' + propOut + 'End';
} else if (propIn) {
endProp = propOut.toLowerCase() + 'end';
}
return endProp;
}
// Test via a getter in the options object to see if the passive property is accessed
var supportsPassive = false;
try {
var opts = Object.defineProperty({}, 'passive', {
get: function() {
supportsPassive = true;
}
});
window.addEventListener("test", null, opts);
} catch (e) {}
var passiveOption = supportsPassive ? { passive: true } : false;
function addEvents(el, obj, preventScrolling) {
for (var prop in obj) {
var option = ['touchstart', 'touchmove'].indexOf(prop) >= 0 && !preventScrolling ? passiveOption : false;
el.addEventListener(prop, obj[prop], option);
}
}
function removeEvents(el, obj) {
for (var prop in obj) {
var option = ['touchstart', 'touchmove'].indexOf(prop) >= 0 ? passiveOption : false;
el.removeEventListener(prop, obj[prop], option);
}
}
function Events() {
return {
topics: {},
on: function (eventName, fn) {
this.topics[eventName] = this.topics[eventName] || [];
this.topics[eventName].push(fn);
},
off: function(eventName, fn) {
if (this.topics[eventName]) {
for (var i = 0; i < this.topics[eventName].length; i++) {
if (this.topics[eventName][i] === fn) {
this.topics[eventName].splice(i, 1);
break;
}
}
}
},
emit: function (eventName, data) {
data.type = eventName;
if (this.topics[eventName]) {
this.topics[eventName].forEach(function(fn) {
fn(data, eventName);
});
}
}
};
}
function jsTransform(element, attr, prefix, postfix, to, duration, callback) {
var tick = Math.min(duration, 10),
unit = (to.indexOf('%') >= 0) ? '%' : 'px',
to = to.replace(unit, ''),
from = Number(element.style[attr].replace(prefix, '').replace(postfix, '').replace(unit, '')),
positionTick = (to - from) / duration * tick,
running;
setTimeout(moveElement, tick);
function moveElement() {
duration -= tick;
from += positionTick;
element.style[attr] = prefix + from + unit + postfix;
if (duration > 0) {
setTimeout(moveElement, tick);
} else {
callback();
}
}
}
// polyfill
if (!Object.keys) {
Object.keys = function (object) {
var keys = [];
for (var name in object) {
if (Object.prototype.hasOwnProperty.call(object, name)) {
keys.push(name);
}
}
return keys;
};
}
if(!("remove" in Element.prototype)){
Element.prototype.remove = function(){
if(this.parentNode) {
this.parentNode.removeChild(this);
}
};
}
var tns = function(options) {
options = extend({
container: '.slider',
mode: 'carousel',
axis: 'horizontal',
items: 1,
gutter: 0,
edgePadding: 0,
fixedWidth: false,
autoWidth: false,
viewportMax: false,
slideBy: 1,
center: false,
controls: true,
controlsPosition: 'top',
controlsText: ['prev', 'next'],
controlsContainer: false,
prevButton: false,
nextButton: false,
nav: true,
navPosition: 'top',
navContainer: false,
navAsThumbnails: false,
arrowKeys: false,
speed: 300,
autoplay: false,
autoplayPosition: 'top',
autoplayTimeout: 5000,
autoplayDirection: 'forward',
autoplayText: ['start', 'stop'],
autoplayHoverPause: false,
autoplayButton: false,
autoplayButtonOutput: true,
autoplayResetOnVisibility: true,
animateIn: 'tns-fadeIn',
animateOut: 'tns-fadeOut',
animateNormal: 'tns-normal',
animateDelay: false,
loop: true,
rewind: false,
autoHeight: false,
responsive: false,
lazyload: false,
lazyloadSelector: '.tns-lazy-img',
touch: true,
mouseDrag: false,
swipeAngle: 15,
nested: false,
preventActionWhenRunning: false,
preventScrollOnTouch: false,
freezable: true,
onInit: false,
useLocalStorage: true
}, options || {});
var doc = document,
win = window,
KEYS = {
ENTER: 13,
SPACE: 32,
LEFT: 37,
RIGHT: 39
},
tnsStorage = {},
localStorageAccess = options.useLocalStorage;
if (localStorageAccess) {
// check browser version and local storage access
var browserInfo = navigator.userAgent;
var uid = new Date;
try {
tnsStorage = win.localStorage;
if (tnsStorage) {
tnsStorage.setItem(uid, uid);
localStorageAccess = tnsStorage.getItem(uid) == uid;
tnsStorage.removeItem(uid);
} else {
localStorageAccess = false;
}
if (!localStorageAccess) { tnsStorage = {}; }
} catch(e) {
localStorageAccess = false;
}
if (localStorageAccess) {
// remove storage when browser version changes
if (tnsStorage['tnsApp'] && tnsStorage['tnsApp'] !== browserInfo) {
['tC', 'tPL', 'tMQ', 'tTf', 't3D', 'tTDu', 'tTDe', 'tADu', 'tADe', 'tTE', 'tAE'].forEach(function(item) { tnsStorage.removeItem(item); });
}
// update browserInfo
localStorage['tnsApp'] = browserInfo;
}
}
var CALC = tnsStorage['tC'] ? checkStorageValue(tnsStorage['tC']) : setLocalStorage(tnsStorage, 'tC', calc(), localStorageAccess),
PERCENTAGELAYOUT = tnsStorage['tPL'] ? checkStorageValue(tnsStorage['tPL']) : setLocalStorage(tnsStorage, 'tPL', percentageLayout(), localStorageAccess),
CSSMQ = tnsStorage['tMQ'] ? checkStorageValue(tnsStorage['tMQ']) : setLocalStorage(tnsStorage, 'tMQ', mediaquerySupport(), localStorageAccess),
TRANSFORM = tnsStorage['tTf'] ? checkStorageValue(tnsStorage['tTf']) : setLocalStorage(tnsStorage, 'tTf', whichProperty('transform'), localStorageAccess),
HAS3DTRANSFORMS = tnsStorage['t3D'] ? checkStorageValue(tnsStorage['t3D']) : setLocalStorage(tnsStorage, 't3D', has3DTransforms(TRANSFORM), localStorageAccess),
TRANSITIONDURATION = tnsStorage['tTDu'] ? checkStorageValue(tnsStorage['tTDu']) : setLocalStorage(tnsStorage, 'tTDu', whichProperty('transitionDuration'), localStorageAccess),
TRANSITIONDELAY = tnsStorage['tTDe'] ? checkStorageValue(tnsStorage['tTDe']) : setLocalStorage(tnsStorage, 'tTDe', whichProperty('transitionDelay'), localStorageAccess),
ANIMATIONDURATION = tnsStorage['tADu'] ? checkStorageValue(tnsStorage['tADu']) : setLocalStorage(tnsStorage, 'tADu', whichProperty('animationDuration'), localStorageAccess),
ANIMATIONDELAY = tnsStorage['tADe'] ? checkStorageValue(tnsStorage['tADe']) : setLocalStorage(tnsStorage, 'tADe', whichProperty('animationDelay'), localStorageAccess),
TRANSITIONEND = tnsStorage['tTE'] ? checkStorageValue(tnsStorage['tTE']) : setLocalStorage(tnsStorage, 'tTE', getEndProperty(TRANSITIONDURATION, 'Transition'), localStorageAccess),
ANIMATIONEND = tnsStorage['tAE'] ? checkStorageValue(tnsStorage['tAE']) : setLocalStorage(tnsStorage, 'tAE', getEndProperty(ANIMATIONDURATION, 'Animation'), localStorageAccess);
// get element nodes from selectors
var supportConsoleWarn = win.console && typeof win.console.warn === "function",
tnsList = ['container', 'controlsContainer', 'prevButton', 'nextButton', 'navContainer', 'autoplayButton'],
optionsElements = {};
tnsList.forEach(function(item) {
if (typeof options[item] === 'string') {
var str = options[item],
el = doc.querySelector(str);
optionsElements[item] = str;
if (el && el.nodeName) {
options[item] = el;
} else {
if (supportConsoleWarn) { console.warn('Can\'t find', options[item]); }
return;
}
}
});
// make sure at least 1 slide
if (options.container.children.length < 1) {
if (supportConsoleWarn) { console.warn('No slides found in', options.container); }
return;
}
// update options
var responsive = options.responsive,
nested = options.nested,
carousel = options.mode === 'carousel' ? true : false;
if (responsive) {
// apply responsive[0] to options and remove it
if (0 in responsive) {
options = extend(options, responsive[0]);
delete responsive[0];
}
var responsiveTem = {};
for (var key in responsive) {
var val = responsive[key];
// update responsive
// from: 300: 2
// to:
// 300: {
// items: 2
// }
val = typeof val === 'number' ? {items: val} : val;
responsiveTem[key] = val;
}
responsive = responsiveTem;
responsiveTem = null;
}
// update options
function updateOptions (obj) {
for (var key in obj) {
if (!carousel) {
if (key === 'slideBy') { obj[key] = 'page'; }
if (key === 'edgePadding') { obj[key] = false; }
if (key === 'autoHeight') { obj[key] = false; }
}
// update responsive options
if (key === 'responsive') { updateOptions(obj[key]); }
}
}
if (!carousel) { updateOptions(options); }
// === define and set variables ===
if (!carousel) {
options.axis = 'horizontal';
options.slideBy = 'page';
options.edgePadding = false;
var animateIn = options.animateIn,
animateOut = options.animateOut,
animateDelay = options.animateDelay,
animateNormal = options.animateNormal;
}
var horizontal = options.axis === 'horizontal' ? true : false,
outerWrapper = doc.createElement('div'),
innerWrapper = doc.createElement('div'),
middleWrapper,
container = options.container,
containerParent = container.parentNode,
containerHTML = container.outerHTML,
slideItems = container.children,
slideCount = slideItems.length,
breakpointZone,
windowWidth = getWindowWidth(),
isOn = false;
if (responsive) { setBreakpointZone(); }
if (carousel) { container.className += ' tns-vpfix'; }
// fixedWidth: viewport > rightBoundary > indexMax
var autoWidth = options.autoWidth,
fixedWidth = getOption('fixedWidth'),
edgePadding = getOption('edgePadding'),
gutter = getOption('gutter'),
viewport = getViewportWidth(),
center = getOption('center'),
items = !autoWidth ? Math.floor(getOption('items')) : 1,
slideBy = getOption('slideBy'),
viewportMax = options.viewportMax || options.fixedWidthViewportWidth,
arrowKeys = getOption('arrowKeys'),
speed = getOption('speed'),
rewind = options.rewind,
loop = rewind ? false : options.loop,
autoHeight = getOption('autoHeight'),
controls = getOption('controls'),
controlsText = getOption('controlsText'),
nav = getOption('nav'),
touch = getOption('touch'),
mouseDrag = getOption('mouseDrag'),
autoplay = getOption('autoplay'),
autoplayTimeout = getOption('autoplayTimeout'),
autoplayText = getOption('autoplayText'),
autoplayHoverPause = getOption('autoplayHoverPause'),
autoplayResetOnVisibility = getOption('autoplayResetOnVisibility'),
sheet = createStyleSheet(),
lazyload = options.lazyload,
lazyloadSelector = options.lazyloadSelector,
slidePositions, // collection of slide positions
slideItemsOut = [],
cloneCount = loop ? getCloneCountForLoop() : 0,
slideCountNew = !carousel ? slideCount + cloneCount : slideCount + cloneCount * 2,
hasRightDeadZone = (fixedWidth || autoWidth) && !loop ? true : false,
rightBoundary = fixedWidth ? getRightBoundary() : null,
updateIndexBeforeTransform = (!carousel || !loop) ? true : false,
// transform
transformAttr = horizontal ? 'left' : 'top',
transformPrefix = '',
transformPostfix = '',
// index
getIndexMax = (function () {
if (fixedWidth) {
return function() { return center && !loop ? slideCount - 1 : Math.ceil(- rightBoundary / (fixedWidth + gutter)); };
} else if (autoWidth) {
return function() {
for (var i = slideCountNew; i--;) {
if (slidePositions[i] >= - rightBoundary) { return i; }
}
};
} else {
return function() {
if (center && carousel && !loop) {
return slideCount - 1;
} else {
return loop || carousel ? Math.max(0, slideCountNew - Math.ceil(items)) : slideCountNew - 1;
}
};
}
})(),
index = getStartIndex(getOption('startIndex')),
indexCached = index,
displayIndex = getCurrentSlide(),
indexMin = 0,
indexMax = !autoWidth ? getIndexMax() : null,
// resize
resizeTimer,
preventActionWhenRunning = options.preventActionWhenRunning,
swipeAngle = options.swipeAngle,
moveDirectionExpected = swipeAngle ? '?' : true,
running = false,
onInit = options.onInit,
events = new Events(),
// id, class
newContainerClasses = ' tns-slider tns-' + options.mode,
slideId = container.id || getSlideId(),
disable = getOption('disable'),
disabled = false,
freezable = options.freezable,
freeze = freezable && !autoWidth ? getFreeze() : false,
frozen = false,
controlsEvents = {
'click': onControlsClick,
'keydown': onControlsKeydown
},
navEvents = {
'click': onNavClick,
'keydown': onNavKeydown
},
hoverEvents = {
'mouseover': mouseoverPause,
'mouseout': mouseoutRestart
},
visibilityEvent = {'visibilitychange': onVisibilityChange},
docmentKeydownEvent = {'keydown': onDocumentKeydown},
touchEvents = {
'touchstart': onPanStart,
'touchmove': onPanMove,
'touchend': onPanEnd,
'touchcancel': onPanEnd
}, dragEvents = {
'mousedown': onPanStart,
'mousemove': onPanMove,
'mouseup': onPanEnd,
'mouseleave': onPanEnd
},
hasControls = hasOption('controls'),
hasNav = hasOption('nav'),
navAsThumbnails = autoWidth ? true : options.navAsThumbnails,
hasAutoplay = hasOption('autoplay'),
hasTouch = hasOption('touch'),
hasMouseDrag = hasOption('mouseDrag'),
slideActiveClass = 'tns-slide-active',
imgCompleteClass = 'tns-complete',
imgEvents = {
'load': onImgLoaded,
'error': onImgFailed
},
imgsComplete,
liveregionCurrent,
preventScroll = options.preventScrollOnTouch === 'force' ? true : false;
// controls
if (hasControls) {
var controlsContainer = options.controlsContainer,
controlsContainerHTML = options.controlsContainer ? options.controlsContainer.outerHTML : '',
prevButton = options.prevButton,
nextButton = options.nextButton,
prevButtonHTML = options.prevButton ? options.prevButton.outerHTML : '',
nextButtonHTML = options.nextButton ? options.nextButton.outerHTML : '',
prevIsButton,
nextIsButton;
}
// nav
if (hasNav) {
var navContainer = options.navContainer,
navContainerHTML = options.navContainer ? options.navContainer.outerHTML : '',
navItems,
pages = autoWidth ? slideCount : getPages(),
pagesCached = 0,
navClicked = -1,
navCurrentIndex = getCurrentNavIndex(),
navCurrentIndexCached = navCurrentIndex,
navActiveClass = 'tns-nav-active',
navStr = 'Carousel Page ',
navStrCurrent = ' (Current Slide)';
}
// autoplay
if (hasAutoplay) {
var autoplayDirection = options.autoplayDirection === 'forward' ? 1 : -1,
autoplayButton = options.autoplayButton,
autoplayButtonHTML = options.autoplayButton ? options.autoplayButton.outerHTML : '',
autoplayHtmlStrings = ['<span class=\'tns-visually-hidden\'>', ' animation</span>'],
autoplayTimer,
animating,
autoplayHoverPaused,
autoplayUserPaused,
autoplayVisibilityPaused;
}
if (hasTouch || hasMouseDrag) {
var initPosition = {},
lastPosition = {},
translateInit,
disX,
disY,
panStart = false,
rafIndex,
getDist = horizontal ?
function(a, b) { return a.x - b.x; } :
function(a, b) { return a.y - b.y; };
}
// disable slider when slidecount <= items
if (!autoWidth) { resetVariblesWhenDisable(disable || freeze); }
if (TRANSFORM) {
transformAttr = TRANSFORM;
transformPrefix = 'translate';
if (HAS3DTRANSFORMS) {
transformPrefix += horizontal ? '3d(' : '3d(0px, ';
transformPostfix = horizontal ? ', 0px, 0px)' : ', 0px)';
} else {
transformPrefix += horizontal ? 'X(' : 'Y(';
transformPostfix = ')';
}
}
if (carousel) { container.className = container.className.replace('tns-vpfix', ''); }
initStructure();
initSheet();
initSliderTransform();
// === COMMON FUNCTIONS === //
function resetVariblesWhenDisable (condition) {
if (condition) {
controls = nav = touch = mouseDrag = arrowKeys = autoplay = autoplayHoverPause = autoplayResetOnVisibility = false;
}
}
function getCurrentSlide () {
var tem = carousel ? index - cloneCount : index;
while (tem < 0) { tem += slideCount; }
return tem%slideCount + 1;
}
function getStartIndex (ind) {
ind = ind ? Math.max(0, Math.min(loop ? slideCount - 1 : slideCount - items, ind)) : 0;
return carousel ? ind + cloneCount : ind;
}
function getAbsIndex (i) {
if (i == null) { i = index; }
if (carousel) { i -= cloneCount; }
while (i < 0) { i += slideCount; }
return Math.floor(i%slideCount);
}
function getCurrentNavIndex () {
var absIndex = getAbsIndex(),
result;
result = navAsThumbnails ? absIndex :
fixedWidth || autoWidth ? Math.ceil((absIndex + 1) * pages / slideCount - 1) :
Math.floor(absIndex / items);
// set active nav to the last one when reaches the right edge
if (!loop && carousel && index === indexMax) { result = pages - 1; }
return result;
}
function getItemsMax () {
// fixedWidth or autoWidth while viewportMax is not available
if (autoWidth || (fixedWidth && !viewportMax)) {
return slideCount - 1;
// most cases
} else {
var str = fixedWidth ? 'fixedWidth' : 'items',
arr = [];
if (fixedWidth || options[str] < slideCount) { arr.push(options[str]); }
if (responsive) {
for (var bp in responsive) {
var tem = responsive[bp][str];
if (tem && (fixedWidth || tem < slideCount)) { arr.push(tem); }
}
}
if (!arr.length) { arr.push(0); }
return Math.ceil(fixedWidth ? viewportMax / Math.min.apply(null, arr) : Math.max.apply(null, arr));
}
}
function getCloneCountForLoop () {
var itemsMax = getItemsMax(),
result = carousel ? Math.ceil((itemsMax * 5 - slideCount)/2) : (itemsMax * 4 - slideCount);
result = Math.max(itemsMax, result);
return hasOption('edgePadding') ? result + 1 : result;
}
function getWindowWidth () {
return win.innerWidth || doc.documentElement.clientWidth || doc.body.clientWidth;
}
function getInsertPosition (pos) {
return pos === 'top' ? 'afterbegin' : 'beforeend';
}
function getClientWidth (el) {
var div = doc.createElement('div'), rect, width;
el.appendChild(div);
rect = div.getBoundingClientRect();
width = rect.right - rect.left;
div.remove();
return width || getClientWidth(el.parentNode);
}
function getViewportWidth () {
var gap = edgePadding ? edgePadding * 2 - gutter : 0;
return getClientWidth(containerParent) - gap;
}
function hasOption (item) {
if (options[item]) {
return true;
} else {
if (responsive) {
for (var bp in responsive) {
if (responsive[bp][item]) { return true; }
}
}
return false;
}
}
// get option:
// fixed width: viewport, fixedWidth, gutter => items
// others: window width => all variables
// all: items => slideBy
function getOption (item, ww) {