forked from danielgindi/jquery-backstretch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jquery.backstretch.js
1526 lines (1245 loc) · 45.5 KB
/
jquery.backstretch.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
/*
* Backstretch
* http://srobbin.com/jquery-plugins/backstretch/
*
* Copyright (c) 2013 Scott Robbin
* Licensed under the MIT license.
*/
;(function ($, window, undefined) {
'use strict';
/** @const */
var YOUTUBE_REGEXP = /^.*(youtu\.be\/|youtube\.com\/v\/|youtube\.com\/embed\/|youtube\.com\/watch\?v=|youtube\.com\/watch\?.*\&v=)([^#\&\?]*).*/i;
/* PLUGIN DEFINITION
* ========================= */
$.fn.backstretch = function (images, options) {
var args = arguments;
/*
* Scroll the page one pixel to get the right window height on iOS
* Pretty harmless for everyone else
*/
if ($(window).scrollTop() === 0 ) {
window.scrollTo(0, 0);
}
var returnValues;
this.each(function (eachIndex) {
var $this = $(this)
, obj = $this.data('backstretch');
// Do we already have an instance attached to this element?
if (obj) {
// Is this a method they're trying to execute?
if (typeof args[0] === 'string' &&
typeof obj[args[0]] === 'function') {
// Call the method
var returnValue = obj[args[0]].apply(obj, Array.prototype.slice.call(args, 1));
if (returnValue === obj) { // If a method is chaining
returnValue = undefined;
}
if (returnValue !== undefined) {
returnValues = returnValues || [];
returnValues[eachIndex] = returnValue;
}
return; // Nothing further to do
}
// Merge the old options with the new
options = $.extend(obj.options, options);
// Remove the old instance
if ( obj.hasOwnProperty('destroy') ) {
obj.destroy(true);
}
}
// We need at least one image
if (!images || (images && images.length === 0)) {
var cssBackgroundImage = $this.css('background-image');
if (cssBackgroundImage && cssBackgroundImage !== 'none') {
images = [ { url: $this.css('backgroundImage').replace(/url\(|\)|"|'/g,"") } ];
} else {
$.error('No images were supplied for Backstretch, or element must have a CSS-defined background image.');
}
}
obj = new Backstretch(this, images, options || {});
$this.data('backstretch', obj);
});
return returnValues ? returnValues.length === 1 ? returnValues[0] : returnValues : this;
};
// If no element is supplied, we'll attach to body
$.backstretch = function (images, options) {
// Return the instance
return $('body')
.backstretch(images, options)
.data('backstretch');
};
// Custom selector
$.expr[':'].backstretch = function(elem) {
return $(elem).data('backstretch') !== undefined;
};
/* DEFAULTS
* ========================= */
$.fn.backstretch.defaults = {
duration: 5000 // Amount of time in between slides (if slideshow)
, transition: 'fade' // Type of transition between slides
, transitionDuration: 0 // Duration of transition between slides
, animateFirst: true // Animate the transition of first image of slideshow in?
, alignX: 0.5 // The x-alignment for the image, can be 'left'|'center'|'right' or any number between 0.0 and 1.0
, alignY: 0.5 // The y-alignment for the image, can be 'top'|'center'|'bottom' or any number between 0.0 and 1.0
, paused: false // Whether the images should slide after given duration
, start: 0 // Index of the first image to show
, preload: 2 // How many images preload at a time?
, preloadSize: 1 // How many images can we preload in parallel?
, resolutionRefreshRate: 2500 // How long to wait before switching resolution?
, resolutionChangeRatioThreshold: 0.1 // How much a change should it be before switching resolution?
};
/* STYLES
*
* Baked-in styles that we'll apply to our elements.
* In an effort to keep the plugin simple, these are not exposed as options.
* That said, anyone can override these in their own stylesheet.
* ========================= */
var styles = {
wrap: {
left: 0
, top: 0
, overflow: 'hidden'
, margin: 0
, padding: 0
, height: '100%'
, width: '100%'
, zIndex: -999999
}
, itemWrapper: {
position: 'absolute'
, display: 'none'
, margin: 0
, padding: 0
, border: 'none'
, width: '100%'
, height: '100%'
, zIndex: -999999
}
, item: {
position: 'absolute'
, margin: 0
, padding: 0
, border: 'none'
, width: '100%'
, height: '100%'
, maxWidth: 'none'
}
};
/* Given an array of different options for an image,
* choose the optimal image for the container size.
*
* Given an image template (a string with {{ width }} and/or
* {{height}} inside) and a container object, returns the
* image url with the exact values for the size of that
* container.
*
* Returns an array of urls optimized for the specified resolution.
*
*/
var optimalSizeImages = (function () {
/* Sorts the array of image sizes based on width */
var widthInsertSort = function (arr) {
for (var i = 1; i < arr.length; i++) {
var tmp = arr[i],
j = i;
while (arr[j - 1] && parseInt(arr[j - 1].width, 10) > parseInt(tmp.width, 10)) {
arr[j] = arr[j - 1];
--j;
}
arr[j] = tmp;
}
return arr;
};
/* Given an array of various sizes of the same image and a container width,
* return the best image.
*/
var selectBest = function (containerWidth, containerHeight, imageSizes) {
var devicePixelRatio = window.devicePixelRatio || 1;
var deviceOrientation = getDeviceOrientation();
var windowOrientation = getWindowOrientation();
var wrapperOrientation = (containerHeight > containerWidth) ?
'portrait' :
(containerWidth > containerHeight ? 'landscape' : 'square');
var lastAllowedImage = 0;
var testWidth;
for (var j = 0, image; j < imageSizes.length; j++) {
image = imageSizes[j];
// In case a new image was pushed in, process it:
if (typeof image === 'string') {
image = imageSizes[j] = { url: image };
}
if (image.pixelRatio && image.pixelRatio !== 'auto' && parseFloat(image.pixelRatio) !== devicePixelRatio) {
// We disallowed choosing this image for current device pixel ratio,
// So skip this one.
continue;
}
if (image.deviceOrientation && image.deviceOrientation !== deviceOrientation) {
// We disallowed choosing this image for current device orientation,
// So skip this one.
continue;
}
if (image.windowOrientation && image.windowOrientation !== deviceOrientation) {
// We disallowed choosing this image for current window orientation,
// So skip this one.
continue;
}
if (image.orientation && image.orientation !== wrapperOrientation) {
// We disallowed choosing this image for current element's orientation,
// So skip this one.
continue;
}
// Mark this one as the last one we investigated
// which does not violate device pixel ratio rules.
// We may choose this one later if there's no match.
lastAllowedImage = j;
// For most images, we match the specified width against element width,
// And enforcing a limit depending on the "pixelRatio" property if specified.
// But if a pixelRatio="auto", then we consider the width as the physical width of the image,
// And match it while considering the device's pixel ratio.
testWidth = containerWidth;
if (image.pixelRatio === 'auto') {
containerWidth *= devicePixelRatio;
}
// Stop when the width of the image is larger or equal to the container width
if (image.width >= testWidth) {
break;
}
}
// Use the image located at where we stopped
return imageSizes[Math.min(j, lastAllowedImage)];
};
var replaceTagsInUrl = function (url, templateReplacer) {
if (typeof url === 'string') {
url = url.replace(/{{(width|height)}}/g, templateReplacer);
} else if (url instanceof Array) {
for (var i = 0; i < url.length; i++) {
if (url[i].src) {
url[i].src = replaceTagsInUrl(url[i].src, templateReplacer);
} else {
url[i] = replaceTagsInUrl(url[i], templateReplacer);
}
}
}
return url;
};
return function ($container, images) {
var containerWidth = $container.width(),
containerHeight = $container.height();
var chosenImages = [];
var templateReplacer = function (match, key) {
if (key === 'width') {
return containerWidth;
}
if (key === 'height') {
return containerHeight;
}
return match;
};
for (var i = 0; i < images.length; i++) {
if ($.isArray(images[i])) {
images[i] = widthInsertSort(images[i]);
var chosen = selectBest(containerWidth, containerHeight, images[i]);
chosenImages.push(chosen);
} else {
// In case a new image was pushed in, process it:
if (typeof images[i] === 'string') {
images[i] = { url: images[i] };
}
var item = $.extend({}, images[i]);
item.url = replaceTagsInUrl(item.url, templateReplacer);
chosenImages.push(item);
}
}
return chosenImages;
};
})();
var isVideoSource = function (source) {
return YOUTUBE_REGEXP.test(source.url) || source.isVideo;
};
/* Preload images */
var preload = (function (sources, startAt, count, batchSize, callback) {
// Plugin cache
var cache = [];
// Wrapper for cache
var caching = function(image){
for (var i = 0; i < cache.length; i++) {
if (cache[i].src === image.src) {
return cache[i];
}
}
cache.push(image);
return image;
};
// Execute callback
var exec = function(sources, callback, last){
if (typeof callback === 'function') {
callback.call(sources, last);
}
};
// Closure to hide cache
return function preload (sources, startAt, count, batchSize, callback){
// Check input data
if (typeof sources === 'undefined') {
return;
}
if (!$.isArray(sources)) {
sources = [sources];
}
if (arguments.length < 5 && typeof arguments[arguments.length - 1] === 'function') {
callback = arguments[arguments.length - 1];
}
startAt = (typeof startAt === 'function' || !startAt) ? 0 : startAt;
count = (typeof count === 'function' || !count || count < 0) ? sources.length : Math.min(count, sources.length);
batchSize = (typeof batchSize === 'function' || !batchSize) ? 1 : batchSize;
if (startAt >= sources.length) {
startAt = 0;
count = 0;
}
if (batchSize < 0) {
batchSize = count;
}
batchSize = Math.min(batchSize, count);
var next = sources.slice(startAt + batchSize, count - batchSize);
sources = sources.slice(startAt, batchSize);
count = sources.length;
// If sources array is empty
if (!count) {
exec(sources, callback, true);
return;
}
// Image loading callback
var countLoaded = 0;
var loaded = function() {
countLoaded++;
if (countLoaded !== count) {
return;
}
exec(sources, callback, !next);
preload(next, 0, 0, batchSize, callback);
};
// Loop sources to preload
var image;
for (var i = 0; i < sources.length; i++) {
if (isVideoSource(sources[i])) {
// Do not preload videos. There are issues with that.
// First - we need to keep an instance of the preloaded and use that exactly, not a copy.
// Second - there are memory issues.
// If there will be a requirement from users - I'll try to implement this.
continue;
} else {
image = new Image();
image.src = sources[i].url;
image = caching(image);
if (image.complete) {
loaded();
} else {
$(image).on('load error', loaded);
}
}
}
};
})();
/* Process images array */
var processImagesArray = function (images) {
var processed = [];
for (var i = 0; i < images.length; i++) {
if (typeof images[i] === 'string') {
processed.push({ url: images[i] });
}
else if ($.isArray(images[i])) {
processed.push(processImagesArray(images[i]));
}
else {
processed.push(processOptions(images[i]));
}
}
return processed;
};
/* Process options */
var processOptions = function (options, required) {
// Convert old options
// centeredX/centeredY are deprecated
if (options.centeredX || options.centeredY) {
if (window.console && window.console.log) {
window.console.log('jquery.backstretch: `centeredX`/`centeredY` is deprecated, please use `alignX`/`alignY`');
}
if (options.centeredX) {
options.alignX = 0.5;
}
if (options.centeredY) {
options.alignY = 0.5;
}
}
// Deprecated spec
if (options.speed !== undefined) {
if (window.console && window.console.log) {
window.console.log('jquery.backstretch: `speed` is deprecated, please use `transitionDuration`');
}
options.transitionDuration = options.speed;
options.transition = 'fade';
}
// Typo
if (options.resolutionChangeRatioTreshold !== undefined) {
window.console.log('jquery.backstretch: `treshold` is a typo!');
options.resolutionChangeRatioThreshold = options.resolutionChangeRatioTreshold;
}
// Current spec that needs processing
if (options.fadeFirst !== undefined) {
options.animateFirst = options.fadeFirst;
}
if (options.fade !== undefined) {
options.transitionDuration = options.fade;
options.transition = 'fade';
}
return processAlignOptions(options);
};
/* Process align options */
var processAlignOptions = function (options, required) {
if (options.alignX === 'left') {
options.alignX = 0.0;
}
else if (options.alignX === 'center') {
options.alignX = 0.5;
}
else if (options.alignX === 'right') {
options.alignX = 1.0;
}
else {
if (options.alignX !== undefined || required) {
options.alignX = parseFloat(options.alignX);
if (isNaN(options.alignX)) {
options.alignX = 0.5;
}
}
}
if (options.alignY === 'top') {
options.alignY = 0.0;
}
else if (options.alignY === 'center') {
options.alignY = 0.5;
}
else if (options.alignY === 'bottom') {
options.alignY = 1.0;
}
else {
if (options.alignX !== undefined || required) {
options.alignY = parseFloat(options.alignY);
if (isNaN(options.alignY)) {
options.alignY = 0.5;
}
}
}
return options;
};
/* CLASS DEFINITION
* ========================= */
var Backstretch = function (container, images, options) {
this.options = $.extend({}, $.fn.backstretch.defaults, options || {});
this.firstShow = true;
// Process options
processOptions(this.options, true);
/* In its simplest form, we allow Backstretch to be called on an image path.
* e.g. $.backstretch('/path/to/image.jpg')
* So, we need to turn this back into an array.
*/
this.images = processImagesArray($.isArray(images) ? images : [images]);
/**
* Paused-Option
*/
if (this.options.paused) {
this.paused = true;
}
/**
* Start-Option (Index)
*/
if (this.options.start >= this.images.length)
{
this.options.start = this.images.length - 1;
}
if (this.options.start < 0)
{
this.options.start = 0;
}
// Convenience reference to know if the container is body.
this.isBody = container === document.body;
/* We're keeping track of a few different elements
*
* Container: the element that Backstretch was called on.
* Wrap: a DIV that we place the image into, so we can hide the overflow.
* Root: Convenience reference to help calculate the correct height.
*/
var $window = $(window);
this.$container = $(container);
this.$root = this.isBody ? supportsFixedPosition ? $window : $(document) : this.$container;
this.originalImages = this.images;
this.images = optimalSizeImages(
this.options.alwaysTestWindowResolution ? $window : this.$root,
this.originalImages);
/**
* Pre-Loading.
* This is the first image, so we will preload a minimum of 1 images.
*/
preload(this.images, this.options.start || 0, this.options.preload || 1);
// Don't create a new wrap if one already exists (from a previous instance of Backstretch)
var $existing = this.$container.children(".backstretch").first();
this.$wrap = $existing.length ? $existing :
$('<div class="backstretch"></div>')
.css(this.options.bypassCss ? {} : styles.wrap)
.appendTo(this.$container);
if (!this.options.bypassCss) {
// Non-body elements need some style adjustments
if (!this.isBody) {
// If the container is statically positioned, we need to make it relative,
// and if no zIndex is defined, we should set it to zero.
var position = this.$container.css('position')
, zIndex = this.$container.css('zIndex');
this.$container.css({
position: position === 'static' ? 'relative' : position
, zIndex: zIndex === 'auto' ? 0 : zIndex
});
// Needs a higher z-index
this.$wrap.css({zIndex: -999998});
}
// Fixed or absolute positioning?
this.$wrap.css({
position: this.isBody && supportsFixedPosition ? 'fixed' : 'absolute'
});
}
// Set the first image
this.index = this.options.start;
this.show(this.index);
// Listen for resize
$window.on('resize.backstretch', $.proxy(this.resize, this))
.on('orientationchange.backstretch', $.proxy(function () {
// Need to do this in order to get the right window height
if (this.isBody && window.pageYOffset === 0) {
window.scrollTo(0, 1);
this.resize();
}
}, this));
};
var performTransition = function (options) {
var transition = options.transition || 'fade';
// Look for multiple options
if (typeof transition === 'string' && transition.indexOf('|') > -1) {
transition = transition.split('|');
}
if (transition instanceof Array) {
transition = transition[Math.round(Math.random() * (transition.length - 1))];
}
var $new = options['new'];
var $old = options['old'] ? options['old'] : $([]);
switch (transition.toString().toLowerCase()) {
default:
case 'fade':
$new.fadeIn({
duration: options.duration,
complete: options.complete,
easing: options.easing || undefined
});
break;
case 'fadeinout':
case 'fade_in_out':
var fadeInNew = function () {
$new.fadeIn({
duration: options.duration / 2,
complete: options.complete,
easing: options.easing || undefined
});
};
if ($old.length) {
$old.fadeOut({
duration: options.duration / 2,
complete: fadeInNew,
easing: options.easing || undefined
});
} else {
fadeInNew();
}
break;
case 'pushleft':
case 'push_left':
case 'pushright':
case 'push_right':
case 'pushup':
case 'push_up':
case 'pushdown':
case 'push_down':
case 'coverleft':
case 'cover_left':
case 'coverright':
case 'cover_right':
case 'coverup':
case 'cover_up':
case 'coverdown':
case 'cover_down':
var transitionParts = transition.match(/^(cover|push)_?(.*)$/);
var animProp = transitionParts[2] === 'left' ? 'right' :
transitionParts[2] === 'right' ? 'left' :
transitionParts[2] === 'down' ? 'top' :
transitionParts[2] === 'up' ? 'bottom' :
'right';
var newCssStart = {
'display': ''
}, newCssAnim = {};
newCssStart[animProp] = '-100%';
newCssAnim[animProp] = 0;
$new
.css(newCssStart)
.animate(newCssAnim, {
duration: options.duration,
complete: function () {
$new.css(animProp, '');
options.complete.apply(this, arguments);
},
easing: options.easing || undefined
});
if (transitionParts[1] === 'push' && $old.length) {
var oldCssAnim = {};
oldCssAnim[animProp] = '100%';
$old
.animate(oldCssAnim, {
duration: options.duration,
complete: function () {
$old.css('display', 'none');
},
easing: options.easing || undefined
});
}
break;
}
};
/* PUBLIC METHODS
* ========================= */
Backstretch.prototype = {
resize: function () {
try {
// Check for a better suited image after the resize
var $resTest = this.options.alwaysTestWindowResolution ? $(window) : this.$root;
var newContainerWidth = $resTest.width();
var newContainerHeight = $resTest.height();
var changeRatioW = newContainerWidth / (this._lastResizeContainerWidth || 0);
var changeRatioH = newContainerHeight / (this._lastResizeContainerHeight || 0);
var resolutionChangeRatioThreshold = this.options.resolutionChangeRatioThreshold || 0.0;
// check for big changes in container size
if ((newContainerWidth !== this._lastResizeContainerWidth ||
newContainerHeight !== this._lastResizeContainerHeight) &&
((Math.abs(changeRatioW - 1) >= resolutionChangeRatioThreshold || isNaN(changeRatioW)) ||
(Math.abs(changeRatioH - 1) >= resolutionChangeRatioThreshold || isNaN(changeRatioH)))) {
this._lastResizeContainerWidth = newContainerWidth;
this._lastResizeContainerHeight = newContainerHeight;
// Big change: rebuild the entire images array
this.images = optimalSizeImages($resTest, this.originalImages);
// Preload them (they will be automatically inserted on the next cycle)
if (this.options.preload) {
preload(this.images, (this.index + 1) % this.images.length, this.options.preload);
}
// In case there is no cycle and the new source is different than the current
if (this.images.length === 1 &&
this._currentImage.url !== this.images[0].url) {
// Wait a little an update the image being showed
var that = this;
clearTimeout(that._selectAnotherResolutionTimeout);
that._selectAnotherResolutionTimeout = setTimeout(function () {
that.show(0);
}, this.options.resolutionRefreshRate);
}
}
var bgCSS = {left: 0, top: 0, right: 'auto', bottom: 'auto'}
, rootWidth = this.isBody ? this.$root.width() : this.$root.innerWidth()
, rootHeight = this.isBody ? ( window.innerHeight ? window.innerHeight : this.$root.height() ) : this.$root.innerHeight()
, bgWidth = rootWidth
, bgHeight = bgWidth / this.$itemWrapper.data('ratio')
, evt = $.Event('backstretch.resize', {
relatedTarget: this.$container[0]
})
, bgOffset
, alignX = this._currentImage.alignX === undefined ? this.options.alignX : this._currentImage.alignX
, alignY = this._currentImage.alignY === undefined ? this.options.alignY : this._currentImage.alignY;
// Make adjustments based on image ratio
if (bgHeight >= rootHeight) {
bgCSS.top = -(bgHeight - rootHeight) * alignY;
} else {
bgHeight = rootHeight;
bgWidth = bgHeight * this.$itemWrapper.data('ratio');
bgOffset = (bgWidth - rootWidth) / 2;
bgCSS.left = -(bgWidth - rootWidth) * alignX;
}
if (!this.options.bypassCss) {
this.$wrap
.css({width: rootWidth, height: rootHeight})
.find('>.backstretch-item').not('.deleteable')
.each(function () {
var $wrapper = $(this);
$wrapper.find('img,video,iframe')
.css({width: bgWidth, height: bgHeight})
.css(bgCSS);
});
}
this.$container.trigger(evt, this);
} catch(err) {
// IE7 seems to trigger resize before the image is loaded.
// This try/catch block is a hack to let it fail gracefully.
}
return this;
}
// Show the slide at a certain position
, show: function (newIndex, overrideOptions) {
// Validate index
if (Math.abs(newIndex) > this.images.length - 1) {
return;
}
// Vars
var that = this
, $oldItemWrapper = that.$wrap.find('>.backstretch-item').addClass('deleteable')
, oldVideoWrapper = that.videoWrapper
, evtOptions = { relatedTarget: that.$container[0] };
// Trigger the "before" event
that.$container.trigger($.Event('backstretch.before', evtOptions), [that, newIndex]);
// Set the new frame index
this.index = newIndex;
var selectedImage = that.images[newIndex];
// Pause the slideshow
clearTimeout(that._cycleTimeout);
// New image
delete that.videoWrapper; // Current item may not be a video
var isVideo = isVideoSource(selectedImage);
if (isVideo) {
that.videoWrapper = new VideoWrapper(selectedImage);
that.$item = that.videoWrapper.$video.css('pointer-events', 'none');
} else {
that.$item = $('<img />');
}
that.$itemWrapper = $('<div class="backstretch-item">')
.append(that.$item);
if (this.options.bypassCss) {
that.$itemWrapper.css({
'display': 'none'
});
} else {
that.$itemWrapper.css(styles.itemWrapper);
that.$item.css(styles.item);
}
that.$item.bind(isVideo ? 'canplay' : 'load', function (e) {
var $this = $(this)
, $wrapper = $this.parent()
, options = $wrapper.data('options');
if (overrideOptions) {
options = $.extend({}, options, overrideOptions);
}
var imgWidth = this.naturalWidth || this.videoWidth || this.width
, imgHeight = this.naturalHeight || this.videoHeight || this.height;
// Save the ratio
$wrapper.data('ratio', imgWidth / imgHeight);
var getOption = function (opt) {
return options[opt] !== undefined ?
options[opt] :
that.options[opt];
};
var transition = getOption('transition');
var transitionEasing = getOption('transitionEasing');
var transitionDuration = getOption('transitionDuration');
// Show the image, then delete the old one
var bringInNextImage = function () {
if (oldVideoWrapper) {
oldVideoWrapper.stop();
oldVideoWrapper.destroy();
}
$oldItemWrapper.remove();
// Resume the slideshow
if (!that.paused && that.images.length > 1) {
that.cycle();
}
// Now we can clear the background on the element, to spare memory
if (!that.options.bypassCss && !that.isBody) {
that.$container.css('background-image', 'none');
}
// Trigger the "after" and "show" events
// "show" is being deprecated
$(['after', 'show']).each(function () {
that.$container.trigger($.Event('backstretch.' + this, evtOptions), [that, newIndex]);
});
if (isVideo) {
that.videoWrapper.play();
}
};
if ((that.firstShow && !that.options.animateFirst) || !transitionDuration || !transition) {
// Avoid transition on first show or if there's no transitionDuration value
$wrapper.show();
bringInNextImage();
} else {
performTransition({
'new': $wrapper,
old: $oldItemWrapper,
transition: transition,
duration: transitionDuration,
easing: transitionEasing,
complete: bringInNextImage
});
}
that.firstShow = false;
// Resize
that.resize();
});
that.$itemWrapper.appendTo(that.$wrap);
that.$item.attr('alt', selectedImage.alt || '');
that.$itemWrapper.data('options', selectedImage);
if (!isVideo) {
that.$item.attr('src', selectedImage.url);
}
that._currentImage = selectedImage;
return that;
}
, current: function () {
return this.index;
}
, next: function () {
var args = Array.prototype.slice.call(arguments, 0);
args.unshift(this.index < this.images.length - 1 ? this.index + 1 : 0);
return this.show.apply(this, args);
}
, prev: function () {
var args = Array.prototype.slice.call(arguments, 0);
args.unshift(this.index === 0 ? this.images.length - 1 : this.index - 1);
return this.show.apply(this, args);
}
, pause: function () {
// Pause the slideshow
this.paused = true;
if (this.videoWrapper) {
this.videoWrapper.pause();
}
return this;
}
, resume: function () {
// Resume the slideshow
this.paused = false;
if (this.videoWrapper) {
this.videoWrapper.play();