forked from bozz/flowgallery
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jquery.flowgallery.js
692 lines (560 loc) · 19.9 KB
/
jquery.flowgallery.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
/*!
* jQuery flowgallery plugin: Cover Flow Image Gallery
* Examples and documentation at: http://flowgallery.org
* Version: 0.7.0 (08-JAN-2013)
* Author: Boris Searles ([email protected])
* Requires jQuery v1.4 or later
* Licensed under the MIT license:
* http://www.opensource.org/licenses/mit-license.php
*/
;(function( $, window, document, undefined ){
"use strict";
var FlowGallery = function(list, config) {
var self = this,
list,
$list, // reference to list as jquery object
options = {}, // merged config options with defaults
centerX = 0, // horizontal center within list
centerY = 0, // vertical center within list
$container = false, // parent element of list
$caption = false, // caption element
activeItem = false, // reference to active FlowItem
activeIndex = 0,
listWidth = 0, // list width (default: screen width)
listHeight = 0, // list height (height of highest image)
flowItems = [], // array of FlowItems
elCounter = 0, // number of list items
resizeWhileDisabled = false,
updateFlowTimer;
// initialize gallery
function init() {
var metadata;
$list = $(list);
// This next line takes advantage of HTML5 data attributes
// to support customization of the plugin on a per-element
// basis. For example,
// <ul id='gallery' data-plugin-options='{"activeIndex": 3}'>...</ul>
metadata = $list.data( 'plugin-options' );
options = $.extend({}, FlowGallery.defaults, config, metadata);
$container = $list.parent();
self.length = $list.children().length;
self.options = options;
initDom();
initFlowItems();
$list.css('visibility', 'visible');
$(window).resize( $.proxy(windowResizeHandler, self) );
if(options.enableKeyNavigation===true) {
$(document).keydown(handleKeyEvents);
}
updateFlow(false);
};
// initialize dom setup and styling
function initDom() {
// set required styling on list element
$list.css({
listStyle: 'none',
overflow: 'hidden',
marginLeft: '0',
paddingLeft: '0',
paddingBottom: '30px',
position: 'relative',
width: '100%'
});
initCaption();
initWrapper();
};
// initialize caption - a single instance is shared by all images
function initCaption() {
$caption = $('<p>', {
'class': 'fg-caption',
css: {
backgroundColor: options.backgroundColor,
display: 'none',
marginTop: '0',
padding: '8px ' + (options.imagePadding+10) + 'px 15px',
position: 'absolute'
}
});
};
// initialize wrapper around gallery - used for positioning caption
function initWrapper() {
var $wrapperElem = $('<div>', {
'class': 'fg-wrapper',
css: {
position: 'relative'
}
})
.append( $list.get(0) )
.append( $caption.get(0) );
$container.append($wrapperElem);
};
function initFlowItems() {
self.enabled = false;
// loop through list items to extract image data and determine list height
$list.children().each(function(index) {
var flowItem = new FlowItem(this, index, options);
if(!flowItem.$el) { return; }
flowItem.$el.one('load', function() {
onItemLoaded.call(flowItem.$el);
}).each(function() {
if($(this).children('img:first')[0].complete) {
$(this).load();
}
});
flowItem.$el.on('click', onItemClicked);
if(!activeItem && options.activeIndex === index) {
flowItem.$el.addClass('active');
activeItem = flowItem;
activeIndex = index;
}
flowItems.push(flowItem);
});
self.enabled = true;
listWidth = $container.width();
centerX = listWidth * 0.5;
};
function onItemLoaded() {
var item = $(this).data('flowItem');
updateListHeight(item.h);
if(!self.activeLoaded && item.index === options.activeIndex) {
self.activeLoaded = true;
clearTimeout(updateFlowTimer);
updateFlowTimer = setTimeout(function () {
updateFlow(options.animateImageLoad);
}, 100);
} else if(self.activeLoaded && (item.th !== options.loadingHeight || item.tw !== options.loadingWidth)) {
clearTimeout(updateFlowTimer);
updateFlowTimer = setTimeout(function () {
updateFlow(options.animateImageLoad);
}, 100);
}
};
function onItemClicked(e) {
var item = $(this).data('flowItem');
if(item !== activeItem) {
var oldIndex = activeIndex;
flowInDir(item.index - oldIndex);
} else if(options.forwardOnActiveClick === true) {
flowInDir(1);
}
};
// only applied after animation of 'active' element
function afterFlowHandler(){
showCaption();
// adjust if width changed (i.e. if scrollbars get displayed)
if($container.width() !== listWidth) {
listWidth = $container.width();
centerX = listWidth * 0.5;
updateFlow();
showCaption();
}
};
// special afterFlow handler for previously active item
function getOldActiveAfterFlowHandler(itemIndex) {
return function() {
var item = flowItems[itemIndex];
item.oldActive = false;
};
};
function updateFlow(animate) {
if(!self.isEnabled()) { return false; }
var config = {},
isBefore = true, // in loop, are we before 'active' item
completeFn = null, // callback method to call after animation (for 'active' item)
currentItem = false,
$listItem = false,
itemsLength = flowItems.length,
i;
// update centerY based on active image
centerY = options.thumbTopOffset === 'auto' ? activeItem.h * 0.5 : options.thumbTopOffset;
for(i = 0; i < itemsLength; i++) {
currentItem = flowItems[i];
$listItem = currentItem.$el;
if($listItem.hasClass('active')) {
config = {
left: (centerX - options.imagePadding - currentItem.w * 0.5) + 'px', top: '0',
width: currentItem.w + 'px',
height: currentItem.h + 'px',
padding: options.imagePadding + 'px'
};
isBefore = false;
completeFn = afterFlowHandler;
// animate list size if active image height has changed
if(listHeight !== currentItem.h) {
listHeight = currentItem.h;
listHeight += options.imagePadding * 2;
if(animate) {
$list.stop().animate({
height: listHeight
}, {
duration: options.duration,
easing: options.easing
});
} else {
$list.height(listHeight);
}
}
} else {
config = {
left: calculateLeftPosition(i, isBefore),
top: (centerY - currentItem.th * 0.5) + 'px'
};
completeFn = null;
// TODO: rethink oldActive check, need to set width/height on first render
// only animate width/height for old active item
// if(currentItem.oldActive) {
config.width = currentItem.tw+'px';
config.height = currentItem.th+'px';
config.padding = options.thumbPadding+'px';
completeFn = getOldActiveAfterFlowHandler(i);
// }
}
if(animate) {
$listItem.stop().animate(config, {
duration: options.duration,
easing: options.easing,
complete: completeFn,
step: function () {
$listItem.css('overflow', 'visible');
}
});
} else {
$listItem.css(config);
if(completeFn) { completeFn(); }
}
}
};
// trigger flow in direction from current active element;
// positive value flows to the right, negative values to the left;
function flowInDir(dir, animate) {
if(!self.isEnabled()) { return false; }
var newIndex = activeIndex + dir;
animate = animate !== undefined ? animate : options.animate;
if(newIndex > flowItems.length - 1 || newIndex < 0) {
return false;
}
activeItem.oldActive = true; // mark old active item
if(dir < 0 && activeIndex > 0) {
flowItems[activeIndex].oldActive = true;
activeIndex += dir;
} else if(dir > 0 && activeIndex < flowItems.length - 1) {
activeIndex += dir;
} else {
return false;
}
activeItem = flowItems[activeIndex];
prepareFlow();
updateFlow(animate);
};
function prepareFlow() {
//if (_options.circular) {
// _circularFlow(currentIndex);
//}
$caption.hide();
$list.find('.active').removeClass('active');
$(activeItem.$el).addClass('active');
// update width (changes if scrollbars disappear)
listWidth = $container.width();
centerX = listWidth*0.5;
};
function calculateLeftPosition(current, isBefore) {
var left = centerX,
i = 0;
if (isBefore) {
left -= flowItems[activeIndex].w * 0.5;
left -= options.imagePadding;
left -= (activeIndex - current) * 10;
left -= (activeIndex - current) * 2 * options.thumbPadding;
for (i = current; i < activeIndex; i++) {
left -= flowItems[i].tw;
}
} else {
left += flowItems[activeIndex].w * 0.5;
left += options.imagePadding;
left += (current - activeIndex) * 10;
left += (current - activeIndex) * 2 * options.thumbPadding;
for (i = activeIndex + 1; i < current; i++) {
left += flowItems[i].tw;
}
}
return left + 'px';
};
// window resize handler - update gallery when window is resized
function windowResizeHandler() {
if(!self.isEnabled()) { resizeWhileDisabled = true; return false; }
listWidth = $container.width();
centerX = listWidth * 0.5;
updateFlow();
showCaption();
};
// show caption under active image
function showCaption() {
if(!activeItem.isLoaded) { return false; }
var fullHeight,
captionText = activeItem.captionText;
if(captionText && captionText.length > 0){
$caption.text(captionText);
$caption.css({
left: centerX - options.imagePadding - activeItem.w * 0.5,
top: activeItem.h + options.imagePadding * 2,
width: activeItem.w - 20
});
// set height of caption as bottom margin for list
fullHeight = activeItem.h + $caption.height() + 40;
//this.$list.height(fullHeight);
$caption.fadeIn('fast');
} else {
// TODO: what happens here?
fullHeight = activeItem.h + 40;
//this.$list.height(fullHeight);
}
};
// set list height to height of tallest image (needed for overflow:hidden)
function updateListHeight(height) {
if(height > listHeight) {
listHeight = height;
listHeight += options.imagePadding * 2;
$list.height(listHeight);
}
};
// handle key events
function handleKeyEvents(e) {
if(e.keyCode === 37) { // right arrow key
flowInDir(-1);
} else if(e.keyCode === 39) { // left arrow key
flowInDir(1);
}
};
// Public API ==================================================
this.length = 0; // number of images in gallery
this.enabled = true; // is gallery currently enabled
this.options = {};
this.getActiveIndex = function() {
return activeIndex;
};
this.next = function(animate) {
flowInDir(1, animate);
return this;
};
this.prev = function(animate) {
flowInDir(-1, animate);
return this;
};
this.jump = function(index, animate) {
flowInDir(index - activeIndex, animate);
return this;
};
this.isEnabled = function() {
return this.enabled===true;
};
this.disable = function() {
this.enabled = false;
return this;
};
this.enable = function() {
this.enabled = true;
// if resize event was fired while disabled, then adjust after
// being enabled again
if(resizeWhileDisabled) {
$.proxy(this.windowResizeHandler, this)();
resizeWhileDisabled = false;
}
return this;
};
this.addFlowItems = function (items, index) {
var newFlowItems = [];
items = Array.isArray(items) ? items : [items];
// adds items to the end if not specified
index = typeof(index) !== 'undefined' ? index : flowItems.length;
// inserting items before activeIndex, need to readjust
if(index <= activeIndex) {
activeIndex += items.length;
}
// updating existing flowItem indices
$.each(flowItems, function (i, flowItem) {
if(i >= index) {
flowItem.index += items.length;
}
});
$.each(items, function(i) {
var flowItem = new FlowItem(this, i + index, options);
if(!flowItem.$el) { return; }
flowItem.$el.on('loaded', onItemLoaded);
flowItem.$el.on('click', onItemClicked);
newFlowItems.push(flowItem);
});
// inserting into flowItems array
Array.prototype.splice.apply(flowItems, [index, 0].concat(newFlowItems));
updateFlow(options.animateImageLoad);
// appending to dom
if(index > 0) {
$list.children('li:nth-child(' + index + ')').after(items);
} else {
$list.prepend(items);
}
};
// initialize
init();
};
// default option values
FlowGallery.defaults = {
activeIndex: 0, // index of image that is initially active
animate: true,
backgroundColor: 'black',
circular: false,
duration: 900, // animation duration (higher value = slower speed)
easing: 'linear',
enableKeyNavigation: true, // enables forward/backward arrow keys for next/previous navigation
forceHeight: false,
forceWidth: false,
forwardOnActiveClick: true, // should clicking on active image, show next image?
imagePadding: 0, // border of active image
loadingClass: "loading", // css class applied to <li> elements of loading images
loadingHeight: 60, // loading height to use if cannot be determined
loadingWidth: 100, // loading width to use if cannot be determined
thumbHeight: 'auto',
thumbPadding: 0, // border of thumbnails
thumbTopOffset: 'auto', // top offset in pixels or 'auto' for centering images within list height
thumbWidth: 'auto',
imageAspectRatio: false, // keeps the images in aspect ratio to original
animateImageLoad: false
};
var FlowItem = function(elem, index, options) {
var self = this,
$img = false;
this.$el = $(elem);
this.index = index;
this.h = 0; // image height
this.th = 0; // thumb height
this.w = 0; // image width
this.tw = 0; // thumb width
this.active = false; // is active image?
this.isLoaded = false; // is image fully loaded?
this.captionText = false; // text specified within 'title' attribute of img
this.oldActive = false; // is this image being animated away from active position?
function init() {
self.h = options.loadingHeight;
self.th = options.loadingHeight;
self.w = options.loadingWidth;
self.tw = options.loadingWidth;
$img = self.$el.find('img');
if($img.length === 0) {
// mark as invalid if no image found
self.$el = false;
return;
}
self.$el.data('flowItem', self);
self.captionText = $img.attr('title');
if(options.forceWidth) {
$img.width(options.forceWidth);
}
// remove image and add 'loading' class
$img.hide().parent('li').addClass(options.loadingClass).css({
height: self.th,
width: self.tw
});
addLoadHandler();
self.$el.css({
backgroundColor: options.backgroundColor,
padding: options.thumbPadding,
position: 'absolute',
textAlign: 'center'
});
$img.css({
cursor: 'pointer',
height: '100%',
imageRendering: 'optimizeQuality', // firefox property
//-ms-interpolation-mode: 'bicubic', // IE property
width: '100%'
});
};
// add handler to images to call after finished loading
function addLoadHandler() {
var img = $img.get(0);
if(img.complete) {
initListItem();
} else {
$img.on('load readystatechange', imageLoadHandler)
.on('error', function () {
$img.css('visibility', 'visible').parent().removeClass(options.loadingClass);
});
}
};
// event handler for image loading
function imageLoadHandler(e) {
var img = $img.get(0);
if (img.complete || (img.readyState === 'complete' && e.type === 'readystatechange')) {
initListItem();
}
};
// load handler for images
function initListItem(){
$img.css('visibility', 'visible').parent('li').removeClass(options.loadingClass);
$img.fadeIn();
self.isLoaded = true;
initImageDimensions();
self.$el.trigger('loaded', self);
};
// determine image dimensions
function initImageDimensions() {
var img = $img.get(0);
if(typeof img.naturalWidth !== 'undefined') {
// update full image dimensions with aspect ratio
if(options.imageAspectRatio) {
if(options.forceWidth && options.forceHeight) {
self.w = options.forceWidth;
self.h = options.forceHeight;
} else if (options.forceWidth) {
self.w = options.forceWidth;
self.h = options.forceWidth / img.naturalWidth * img.naturalHeight;
} else if (options.forceHeight) {
self.w = options.forceHeight / img.naturalHeight * img.naturalWidth;
self.h = options.forceHeight;
} else {
self.w = img.naturalWidth || img.width;
self.h = img.naturalHeight || img.height;
}
} else {
// ignore aspect ratio
self.w = options.forceWidth || img.naturalWidth || img.width;
self.h = options.forceHeight || img.naturalHeight || img.height;
}
} else {
var tmpImg = new Image();
tmpImg.src = $img.attr('src');
self.w = tmpImg.width;
self.h = tmpImg.height;
}
// update thumbnail dimensions
if(options.thumbWidth === 'auto' && options.thumbHeight === 'auto') {
self.tw = options.loadingWidth;
self.th = Math.round(self.h * options.loadingWidth / self.w);
} else if (options.thumbHeight === 'auto') {
self.tw = options.thumbWidth;
self.th = Math.round(self.h * Number(options.thumbWidth) / self.w);
} else if (options.thumbWidth === 'auto') {
self.tw = Math.round(self.w * Number(options.thumbHeight) / self.h);
self.th = options.thumbHeight;
} else {
self.tw = options.thumbWidth;
self.th = options.thumbHeight;
}
};
// Public API ==================================================
init();
};
/** Basic jQuery plugin setup */
$.fn.flowgallery = function(options) {
return this.each(function() {
var element = $(this);
// Return early if this element already has a plugin instance
if (element.data('flowgallery')) { return; }
// pass options to plugin constructor
var flowgallery = new FlowGallery(this, options);
// Store plugin object in this element's data
element.data('flowgallery', flowgallery);
});
};
// default options
$.fn.flowgallery.defaults = FlowGallery.defaults;
})( jQuery, window , document );