-
Notifications
You must be signed in to change notification settings - Fork 31
/
jquery.scrollstory.js
1577 lines (1301 loc) · 44.2 KB
/
jquery.scrollstory.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
/**
* @preserve ScrollStory - vVERSIONXXX - YYYY-MM-DDXXX
* https://github.com/sjwilliams/scrollstory
* Copyright (c) 2017 Josh Williams; Licensed MIT
*/
(function(factory) {
if (typeof define === 'function' && define.amd) {
define(['jquery'], factory);
} else {
factory(jQuery);
}
}(function($, undefined) {
var pluginName = 'scrollStory';
var eventNameSpace = '.' + pluginName;
var defaults = {
// jquery object, class selector string, or array of values, or null (to use existing DOM)
content: null,
// Only used if content null. Should be a class selector
contentSelector: '.story',
// Left/right keys to navigate
keyboard: true,
// Offset from top used in the programatic scrolling of an
// item to the focus position. Useful in the case of thinks like
// top nav that might obscure part of an item if it goes to 0.
scrollOffset: 0,
// Offset from top to trigger a change
triggerOffset: 0,
// Event to monitor. Can be a name for an event on the $(window), or
// a function that defines custom behavior. Defaults to native scroll event.
scrollEvent: 'scroll',
// Automatically activate the first item on load,
// regardless of its position relative to the offset
autoActivateFirstItem: false,
// Disable last item -- and the entire widget -- once it's scroll beyond the trigger point
disablePastLastItem: true,
// Automated scroll speed in ms. Set to 0 to remove animation.
speed: 800,
// Scroll easing. 'swing' or 'linear', unless an external plugin provides others
// http://api.jquery.com/animate/
easing: 'swing',
// // scroll-based events are either 'debounce' or 'throttle'
throttleType: 'throttle',
// frequency in milliseconds to perform scroll-based functions. Scrolling functions
// can be CPU intense, so higher number can help performance.
scrollSensitivity: 100,
// options to pass to underscore's throttle or debounce for scroll
// see: http://underscorejs.org/#throttle && http://underscorejs.org/#debounce
throttleTypeOptions: null,
// Update offsets after likely repaints, like window resizes and filters
autoUpdateOffsets: true,
debug: false,
// whether or not the scroll checking is enabled.
enabled: true,
setup: $.noop,
destroy: $.noop,
itembuild: $.noop,
itemfocus: $.noop,
itemblur: $.noop,
itemfilter: $.noop,
itemunfilter: $.noop,
itementerviewport: $.noop,
itemexitviewport: $.noop,
categoryfocus: $.noop,
categeryblur: $.noop,
containeractive: $.noop,
containerinactive: $.noop,
containerresize: $.noop,
containerscroll: $.noop,
updateoffsets: $.noop,
triggeroffsetupdate: $.noop,
scrolloffsetupdate: $.noop,
complete: $.noop
};
// static across all plugin instances
// so we can uniquely ID elements
var instanceCounter = 0;
/**
* Utility methods
*
* debounce() and throttle() are from on Underscore.js:
* https://github.com/jashkenas/underscore
*/
/**
* Underscore's now:
* http://underscorejs.org/now
*/
var dateNow = Date.now || function() {
return new Date().getTime();
};
/**
* Underscore's debounce:
* http://underscorejs.org/#debounce
*/
var debounce = function(func, wait, immediate) {
var result;
var timeout = null;
return function() {
var context = this,
args = arguments;
var later = function() {
timeout = null;
if (!immediate) {
result = func.apply(context, args);
}
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) {
result = func.apply(context, args);
}
return result;
};
};
/**
* Underscore's throttle:
* http://underscorejs.org/#throttle
*/
var throttle = function(func, wait, options) {
var context, args, result;
var timeout = null;
var previous = 0;
options || (options = {});
var later = function() {
previous = options.leading === false ? 0 : dateNow();
timeout = null;
result = func.apply(context, args);
};
return function() {
var now = dateNow();
if (!previous && options.leading === false) {
previous = now;
}
var remaining = wait - (now - previous);
context = this;
args = arguments;
if (remaining <= 0) {
clearTimeout(timeout);
timeout = null;
previous = now;
result = func.apply(context, args);
} else if (!timeout && options.trailing !== false) {
timeout = setTimeout(later, remaining);
}
return result;
};
};
var $window = $(window);
var winHeight = $window.height(); // cached. updated via _handleResize()
/**
* Given a scroll/trigger offset, determine
* its pixel value from the top of the viewport.
*
* If number or number-like string (30 or '30'), return that
* number. (30)
*
* If it's a percentage string ('30%'), convert to pixels
* based on the height of the viewport. (eg: 395)
*
* @param {String/Number} offset
* @return {Number}
*/
var offsetToPx = function(offset){
var pxOffset;
if (offsetIsAPercentage(offset)) {
pxOffset = offset.slice(0, -1);
pxOffset = Math.round(winHeight * (parseInt(pxOffset, 10)/100) );
} else {
pxOffset = parseInt(offset, 10);
}
return pxOffset;
};
var offsetIsAPercentage = function(offset){
return typeof offset === 'string' && offset.slice(-1) === '%';
};
function ScrollStory(element, options) {
this.el = element;
this.$el = $(element);
this.options = $.extend({}, defaults, options);
this.useNativeScroll = (typeof this.options.scrollEvent === 'string') && (this.options.scrollEvent.indexOf('scroll') === 0);
this._defaults = defaults;
this._name = pluginName;
this._instanceId = (function() {
return pluginName + '_' + instanceCounter;
})();
this.init();
}
ScrollStory.prototype = {
init: function() {
/**
* List of all items, and a quick lockup hash
* Data populated via _prepItems* methods
*/
this._items = [];
this._itemsById = {};
this._categories = [];
this._tags = [];
this._isActive = false;
this._activeItem;
this._previousItems = [];
/**
* Attach handlers before any events are dispatched
*/
this.$el.on('setup'+eventNameSpace, this._onSetup.bind(this));
this.$el.on('destroy'+eventNameSpace, this._onDestroy.bind(this));
this.$el.on('containeractive'+eventNameSpace, this._onContainerActive.bind(this));
this.$el.on('containerinactive'+eventNameSpace, this._onContainerInactive.bind(this));
this.$el.on('itemblur'+eventNameSpace, this._onItemBlur.bind(this));
this.$el.on('itemfocus'+eventNameSpace, this._onItemFocus.bind(this));
this.$el.on('itementerviewport'+eventNameSpace, this._onItemEnterViewport.bind(this));
this.$el.on('itemexitviewport'+eventNameSpace, this._onItemExitViewport.bind(this));
this.$el.on('itemfilter'+eventNameSpace, this._onItemFilter.bind(this));
this.$el.on('itemunfilter'+eventNameSpace, this._onItemUnfilter.bind(this));
this.$el.on('categoryfocus'+eventNameSpace, this._onCategoryFocus.bind(this));
this.$el.on('triggeroffsetupdate'+eventNameSpace, this._onTriggerOffsetUpdate.bind(this));
/**
* Run before any items have been added, allows
* for user manipulation of page before ScrollStory
* acts on anything.
*/
this._trigger('setup', null, this);
/**
* Convert data from outside of widget into
* items and, if needed, categories of items.
*
* Don't 'handleRepaints' just yet, as that'll
* set an active item. We want to do that after
* our 'complete' event is triggered.
*/
this.addItems(this.options.content, {
handleRepaint: false
});
// 1. offsets need to be accurate before 'complete'
this.updateOffsets();
// 2. handle any user actions
this._trigger('complete', null, this);
// 3. Set active item, and double check
// scroll position and offsets.
if(this.options.enabled){
this._handleRepaint();
}
/**
* Bind keyboard events
*/
if (this.options.keyboard) {
$(document).keydown(function(e){
var captured = true;
switch (e.keyCode) {
case 37:
if (e.metaKey) {return;} // ignore ctrl/cmd left, as browsers use that to go back in history
this.previous();
break; // left arrow
case 39:
this.next();
break; // right arrow
default:
captured = false;
}
return !captured;
}.bind(this));
}
/**
* Debug UI
*/
this.$trigger = $('<div class="' + pluginName + 'Trigger"></div>').css({
position: 'fixed',
width: '100%',
height: '1px',
top: offsetToPx(this.options.triggerOffset) + 'px',
left: '0px',
backgroundColor: '#ff0000',
'-webkit-transform': 'translateZ(0)',
'-webkit-backface-visibility': 'hidden',
zIndex: 1000
}).attr('id', pluginName + 'Trigger-' + this._instanceId);
if (this.options.debug) {
this.$trigger.appendTo('body');
}
/**
* Watch either native scroll events, throttled by
* this.options.scrollSensitivity, or a custom event
* that implements its own throttling.
*
* Bind these events after 'complete' trigger so no
* items are active when those callbacks runs.
*/
var scrollThrottle, scrollHandler;
if(this.useNativeScroll){
// bind and throttle native scroll
scrollThrottle = (this.options.throttleType === 'throttle') ? throttle : debounce;
scrollHandler = scrollThrottle(this._handleScroll.bind(this), this.options.scrollSensitivity, this.options.throttleTypeOptions);
$window.on('scroll'+eventNameSpace, scrollHandler);
} else {
// bind but don't throttle custom event
scrollHandler = this._handleScroll.bind(this);
// if custom event is a function, it'll need
// to call the scroll handler manually, like so:
//
// $container.scrollStory({
// scrollEvent: function(cb){
// // custom scroll event on nytimes.com
// PageManager.on('nyt:page-scroll', function(){
// // do something interesting if you like
// // and then call the passed in handler();
// cb();
// });
// }
// });
//
//
// Otherwise, it's a string representing an event on the
// window to subscribe to, like so:
//
// // some code dispatching throttled events
// $window.trigger('nytg-scroll');
//
// $container.scrollStory({
// scrollEvent: 'nytg-scroll'
// });
//
if (typeof this.options.scrollEvent === 'function') {
this.options.scrollEvent(scrollHandler);
} else {
$window.on(this.options.scrollEvent+eventNameSpace, function(){
scrollHandler();
});
}
}
// anything that might cause a repaint
var resizeThrottle = debounce(this._handleResize, 100);
$window.on('DOMContentLoaded'+eventNameSpace + ' load'+eventNameSpace + ' resize'+eventNameSpace, resizeThrottle.bind(this));
instanceCounter = instanceCounter + 1;
},
/**
* Get current item's index,
* or set the current item with an index.
* @param {Number} index
* @param {Function} callback
* @return {Number} index of active item
*/
index: function(index, callback) {
if (typeof index === 'number' && this.getItemByIndex(index)) {
this.setActiveItem(this.getItemByIndex(index), {}, callback);
} else {
return this.getActiveItem().index;
}
},
/**
* Convenience method to navigate to next item
*
* @param {Number} _index -- an optional index. Used to recursively find unflitered item
*/
next: function(_index) {
var currentIndex = _index || this.index();
var nextItem;
if (typeof currentIndex === 'number') {
nextItem = this.getItemByIndex(currentIndex + 1);
// valid index and item
if (nextItem) {
// proceed if not filtered. if filtered try the one after that.
if (!nextItem.filtered) {
this.index(currentIndex + 1);
} else {
this.next(currentIndex + 1);
}
}
}
},
/**
* Convenience method to navigate to previous item
*
* @param {Number} _index -- an optional index. Used to recursively find unflitered item
*/
previous: function(_index) {
var currentIndex = _index || this.index();
var previousItem;
if (typeof currentIndex === 'number') {
previousItem = this.getItemByIndex(currentIndex - 1);
// valid index and item
if (previousItem) {
// proceed if not filtered. if filtered try the one before that.
if (!previousItem.filtered) {
this.index(currentIndex - 1);
} else {
this.previous(currentIndex - 1);
}
}
}
},
/**
* The active item object.
*
* @return {Object}
*/
getActiveItem: function() {
return this._activeItem;
},
/**
* Given an item object, make it active,
* including updating its scroll position.
*
* @param {Object} item
*/
setActiveItem: function(item, options, callback) {
options = options || {};
// verify item
if (item.id && this.getItemById(item.id)) {
this._scrollToItem(item, options, callback);
}
},
/**
* Iterate over each item, passing the item to a callback.
*
* this.each(function(item){ console.log(item.id) });
*
* @param {Function}
*/
each: function(callback) {
this.applyToAllItems(callback);
},
/**
* Return number of items
* @return {Number}
*/
getLength: function() {
return this.getItems().length;
},
/**
* Return array of all items
* @return {Array}
*/
getItems: function() {
return this._items;
},
/**
* Given an item id, return item object with that id.
*
* @param {string} id
* @return {Object}
*/
getItemById: function(id) {
return this._itemsById[id];
},
/**
* Given an item index, return item object with that index.
*
* @param {Integer} index
* @return {Object}
*/
getItemByIndex: function(index) {
return this._items[index];
},
/**
* Return an array of items that pass an abritrary truth test.
*
* Example: this.getItemsBy(function(item){return item.data.slug=='josh_williams'})
*
* @param {Function} truthTest The function to check all items against
* @return {Array} Array of item objects
*/
getItemsBy: function(truthTest) {
if (typeof truthTest !== 'function') {
throw new Error('You must provide a truthTest function');
}
return this.getItems().filter(function(item) {
return truthTest(item);
});
},
/**
* Returns an array of items where all the properties
* match an item's properties. Property tests can be
* any combination of:
*
* 1. Values
* this.getItemsWhere({index:2});
* this.getItemsWhere({filtered:false});
* this.getItemsWhere({category:'cats', width: 300});
*
* 2. Methods that return a value
* this.getItemsWhere({width: function(width){ return 216 + 300;}});
*
* 3. Methods that return a boolean
* this.getItemsWhere({index: function(index){ return index > 2; } });
*
* Mix and match:
* this.getItemsWehre({filtered:false, index: function(index){ return index < 30;} })
*
* @param {Object} properties
* @return {Array} Array of item objects
*/
getItemsWhere: function(properties) {
var keys,
items = []; // empty if properties obj not passed in
if ($.isPlainObject(properties)) {
keys = Object.keys(properties); // properties to check in each item
items = this.getItemsBy(function(item) {
var isMatch = keys.every(function(key) {
var match;
// type 3, method that runs a boolean
if (typeof properties[key] === 'function') {
match = properties[key](item[key]);
// type 2, method that runs a value
if (typeof match !== 'boolean') {
match = item[key] === match;
}
} else {
// type 1, value
match = item[key] === properties[key];
}
return match;
});
if (isMatch) {
return item;
}
});
}
return items;
},
/**
* Array of items that are atleast partially visible
*
* @return {Array}
*/
getItemsInViewport: function() {
return this.getItemsWhere({
inViewport: true
});
},
/**
* Most recently active item.
*
* @return {Object}
*/
getPreviousItem: function() {
return this._previousItems[0];
},
/**
* Array of items that were previously
* active, with most recently active
* at the front of the array.
*
* @return {Array}
*/
getPreviousItems: function() {
return this._previousItems;
},
/**
* Progress of the scroll needed to activate the
* last item on a 0.0 - 1.0 scale.
*
* 0 means the first item isn't yet active,
* and 1 means the last item is active, or
* has already been scrolled beyond active.
*
* @return {[type]} [description]
*/
getPercentScrollToLastItem: function() {
return this._percentScrollToLastItem || 0;
},
/**
* Progress of the entire scroll distance, from the start
* of the first item a '0', until the very end of the last
* item, which is '1';
*/
getScrollComplete: function() {
return this._totalScrollComplete || 0;
},
/**
* Return an array of all filtered items.
* @return {Array}
*/
getFilteredItems: function() {
return this.getItemsWhere({
filtered: true
});
},
/**
* Return an array of all unfiltered items.
* @return {Array}
*/
getUnFilteredItems: function() {
return this.getItemsWhere({
filtered: false
});
},
/**
* Return an array of all items belonging to a category.
*
* @param {String} categorySlug
* @return {Array}
*/
getItemsByCategory: function(categorySlug) {
return this.getItemsWhere({
category: categorySlug
});
},
/**
* Return an array of all category slugs
*
* @return {Array}
*/
getCategorySlugs: function() {
return this._categories;
},
/**
* Change an item's status to filtered.
*
* @param {Object} item
*/
filter: function(item) {
if (!item.filtered) {
item.filtered = true;
this._trigger('itemfilter', null, item);
}
},
/**
* Change an item's status to unfiltered.
*
* @param {Object} item
*/
unfilter: function(item) {
if (item.filtered) {
item.filtered = false;
this._trigger('itemunfilter', null, item);
}
},
/**
* Change all items' status to filtered.
*
* @param {Function} callback
*/
filterAll: function(callback) {
callback = ($.isFunction(callback)) ? callback.bind(this) : $.noop;
var filterFnc = this.filter.bind(this);
this.getItems().forEach(filterFnc);
},
/**
* Change all items' status to unfiltered.
*
* @param {Function} callback
*/
unfilterAll: function(callback) {
callback = ($.isFunction(callback)) ? callback.bind(this) : $.noop;
var unfilterFnc = this.unfilter.bind(this);
this.getItems().forEach(unfilterFnc);
},
/**
* Filter items that pass an abritrary truth test. This is a light
* wrapper around `getItemsBy()` and `filter()`.
*
* Example: this.filterBy(function(item){return item.data.last_name === 'williams'})
*
* @param {Function} truthTest The function to check all items against
* @param {Function} callback
*/
filterBy: function(truthTest, callback) {
callback = ($.isFunction(callback)) ? callback.bind(this) : $.noop;
var filterFnc = this.filter.bind(this);
this.getItemsBy(truthTest).forEach(filterFnc);
callback();
},
/**
* Filter items where all the properties match an item's properties. This
* is a light wrapper around `getItemsWhere()` and `filter()`. See `getItemsWhere()`
* for more options and examples.
*
* Example: this.filterWhere({index:2})
*
* @param {Function} truthTest The function to check all items against
* @param {Function} callback
*/
filterWhere: function(properties, callback) {
callback = ($.isFunction(callback)) ? callback.bind(this) : $.noop;
var filterFnc = this.filter.bind(this);
this.getItemsWhere(properties).forEach(filterFnc);
callback();
},
/**
* Whether or not any of the item objects are active.
*
* @return {Boolean}
*/
isContainerActive: function() {
return this._isActive;
},
/**
* Disable scroll updates. This is useful in the
* rare case when you want to manipulate the page
* but not have ScrollStory continue to check
* positions, fire events, etc. Usually a `disable`
* is temporary and followed by an `enable`.
*/
disable: function() {
this.options.enabled = false;
},
/**
* Enable scroll updates
*/
enable: function() {
this.options.enabled = true;
},
/**
* Update trigger offset. This is useful if a client
* app needs to, post-instantiation, change the trigger
* point, like after a window resize.
*
* @param {Number} offset
*/
updateTriggerOffset: function(offset) {
this.options.triggerOffset = offset;
this.updateOffsets();
this._trigger('triggeroffsetupdate', null, offsetToPx(offset));
},
/**
* Update scroll offset. This is useful if a client
* app needs to, post-instantiation, change the scroll
* offset, like after a window resize.
* @param {Number} offset
*/
updateScrollOffset: function(offset) {
this.options.scrollOffset = offset;
this.updateOffsets();
this._trigger('scrolloffsetupdate', null, offsetToPx(offset));
},
/**
* Determine which item should be active,
* and then make it so.
*/
_setActiveItem: function() {
// top of the container is above the trigger point and the bottom is still below trigger point.
var containerInActiveArea = (this._distanceToFirstItemTopOffset <= 0 && (Math.abs(this._distanceToOffset) - this._height) < 0);
// only check items that aren't filtered
var items = this.getItemsWhere({
filtered: false
});
var activeItem;
items.forEach(function(item) {
// item has to have crossed the trigger offset
if (item.adjustedDistanceToOffset <= 0) {
if (!activeItem) {
activeItem = item;
} else {
// closer to trigger point than previously found item?
if (activeItem.adjustedDistanceToOffset < item.adjustedDistanceToOffset) {
activeItem = item;
}
}
}
});
// double check conditions around an active item
if (activeItem && !containerInActiveArea && this.options.disablePastLastItem) {
activeItem = false;
// not yet scrolled in, but auto-activate is set to true
} else if (!activeItem && this.options.autoActivateFirstItem && items.length > 0) {
activeItem = items[0];
}
if (activeItem) {
this._focusItem(activeItem);
// container
if (!this._isActive) {
this._isActive = true;
this._trigger('containeractive');
}
} else {
this._blurAllItems();
// container
if (this._isActive) {
this._isActive = false;
this._trigger('containerinactive');
}
}
},
/**
* Scroll to an item, making it active.
*
* @param {Object} item
* @param {Object} opts
* @param {Function} callback
*/
_scrollToItem: function(item, opts, callback) {
callback = ($.isFunction(callback)) ? callback.bind(this) : $.noop;
/**
* Allows global scroll options to be overridden
* in one of two ways:
*
* 1. Higher priority: Passed in to scrollToItem directly via opts obj.
* 2. Lower priority: options set as an item.* property
*/
opts = $.extend(true, {
// prefer item.scrollOffset over this.options.scrollOffset
scrollOffset: (item.scrollOffset !== false) ? offsetToPx(item.scrollOffset) : offsetToPx(this.options.scrollOffset),
speed: this.options.speed,
easing: this.options.easing
}, opts);
// because we animate to body and html for maximum compatiblity,
// we only want the callback to fire once. jQuery will call it
// once for each element otherwise
var debouncedCallback = debounce(callback, 100);
// position to travel to
var scrolllTop = item.el.offset().top - offsetToPx(opts.scrollOffset);
$('html, body').stop(true).animate({
scrollTop: scrolllTop
}, opts.speed, opts.easing, debouncedCallback);
},
/**
* Excecute a callback function that expects an
* item as its paramamter for each items.
*
* Optionally, a item or array of items of exceptions
* can be passed in. They'll not call the callback.
*
* @param {Function} callback Method to call, and pass in exepctions
* @param {Object/Array} exceptions
*/
applyToAllItems: function(callback, exceptions) {
exceptions = ($.isArray(exceptions)) ? exceptions : [exceptions];
callback = ($.isFunction(callback)) ? callback.bind(this) : $.noop;
var items = this.getItems();
var i = 0;
var length = items.length;
var item;
for (i = 0; i < length; i++) {
item = items[i];
if (exceptions.indexOf(item) === -1) {
callback(item, i);
}
}
},
/**
* Unfocus all items.
*
* @param {Object/Array} exceptions item or array of items to not blur
*/
_blurAllItems: function(exceptions) {
this.applyToAllItems(this._blurItem.bind(this), exceptions);