/
jquery.scrollz.js
795 lines (595 loc) · 24.7 KB
/
jquery.scrollz.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
/*! jQuery Scrollz - v1.0.3 - 2013-02-28
* https://github.com/zippy1978/jquery.scrollz
* Copyright (c) 2013 Gilles Grousset; Licensed MIT, GPL */
(function($) {
// Methods definition
var methods = {
/* Initialization */
init : function(options) {
// Default options
var settings = $.extend( {
'pull' : false, // Pull support
'pullHeaderHTML' : {
'initial' : '<div><div class="icon"/><div class="label">Pull to refresh</div></div>', // Pull header on initial state
'release' : '<div><div class="icon"/><div class="label">Release to refresh</div></div>', // Pull header on release state
'waiting' : '<div><div class="icon"/><div class="label">Refreshing...</div></div>' // Pull header waiting state
},
'inertia' : true, // Inertia support
'emulateTouchEvents' : false // Emulate touch events when device is not a touch device
}, options);
// Define easeOutCubic easing function (if not defined yet)
if ($.easing.easeOutCubic === undefined) {
$.easing.easeOutCubic = function (x, t, b, c, d) {
return c*((t=t/d-1)*t*t + 1) + b;
};
}
// Define scrollstart and scrollstop special events (if not defined yet)
// As explained here: http://james.padolsey.com/javascript/special-scroll-events-for-jquery
if (!$.event.special.scrollstart && !$.event.special.scrollend) {
var special = $.event.special,
uid1 = 'D' + (+new Date()),
uid2 = 'D' + (+new Date() + 1);
special.scrollstart = {
setup: function() {
var timer,
handler = function(evt) {
var _self = this,
_args = arguments;
if (timer) {
clearTimeout(timer);
} else {
evt.type = 'scrollstart';
$.event.dispatch.apply(_self, _args);
}
timer = setTimeout(function(){
timer = null;
}, special.scrollstop.latency);
};
$(this).bind('scroll', handler).data(uid1, handler);
},
teardown: function(){
$(this).unbind('scroll', $(this).data(uid1));
}
};
special.scrollstop = {
latency: 300,
setup: function() {
var timer,
handler = function(evt) {
var _self = this,
_args = arguments;
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(function(){
timer = null;
evt.type = 'scrollstop';
$.event.dispatch.apply(_self, _args);
}, special.scrollstop.latency);
};
$(this).bind('scroll', handler).data(uid2, handler);
},
teardown: function() {
$(this).unbind('scroll', $(this).data(uid2));
}
};
}
return this.each(function() {
var $this = $(this);
// If the plugin hasn't been initialized yet
if (!_isInitialized($this)) {
// Store options
$this.data('options', settings);
// Create markup
_createMarkup($this);
var container = _getMarkupCache($this, 'container');
// Store container initial position
_putTrackingData($this, 'initialScrollPosition', container.scrollTop());
// Add touch start listener
container.bind(_getTouchEventName($this, 'touchstart'), function(event) {
// Handle
_handleTouchStartEvent(event, $this);
});
// Add touch move listener
container.bind(_getTouchEventName($this, 'touchmove'), function(event) {
// Prevent default behaviour
event.preventDefault();
// Handle
_handleTouchMoveEvent(event, $this);
});
// Add touch end listener
container.bind(_getTouchEventName($this, 'touchend'), function(event) {
// Prevent default behaviour
// Handle
_handleTouchEndEvent(event, $this);
});
// Add touch end listener when outside container (in case the last touch is outside the container)
$('*').not(container).bind(_getTouchEventName($this, 'touchend'), function(event) {
// Handle
_handleTouchEndEvent(event, $this);
});
// Add mousewheel listener
container.bind('mousewheel DOMMouseScroll', function(event) {
// Prevent default behaviour
event.preventDefault();
// Handle
_handleMouseWheelEvent(event, $this);
});
// Add scroll listener
container.scroll(function(event) {
// Handle
_handleScrollEvent(event, $this);
});
// Add scroll start listener
container.bind('scrollstart', function(event) {
// Handle
_handleScrollStartEvent(event, $this);
});
// Add scroll stop listener
container.bind('scrollstop', function(event) {
// Handle
_handleScrollStopEvent(event, $this);
});
// Mark plugin as initialized
$this.data('scrollzInitialized', true);
}
});
},
/* Sets container height */
height: function(height) {
return this.each(function() {
var $this = $(this);
// If plugin initialized
if (_isInitialized($this)) {
var settings = $this.data('options');
var container = _getMarkupCache($this, 'container');
container.height(height);
$this.css('min-height', container.css('height'));
}
});
},
/* Hides pull header */
hidePullHeader: function(animated) {
// If animated parameter is not defined : then it is set to true
animated = typeof animated !== 'undefined' ? animated : true;
return this.each(function() {
var $this = $(this);
// If plugin initialized
if (_isInitialized($this)) {
var settings = $this.data('options');
var container = _getMarkupCache($this, 'container');
if (settings.pull) {
if (animated) {
container.animate({scrollTop: _getPullHeaderHeight($this)}, 'fast', function() {
_changePullHeaderState($this, 'initial');
});
} else {
container.scrollTop(_getPullHeaderHeight($this));
_changePullHeaderState($this, 'initial');
}
}
}
});
}
};
// Private functions
/* Tests if current device is a touch device. */
function _isTouchDevice() {
return ('ontouchstart' in document.documentElement);
}
/* Get pull header height. */
function _getPullHeaderHeight(instance) {
var contentWrapper = _getMarkupCache(instance, 'contentWrapper');
var pullHeader = _getMarkupCache(instance, 'pullHeader');
if (pullHeader) {
return pullHeader.outerHeight(true);
} else {
return 0;
}
}
/* Converts a touch event name into a supported event name (in case the device is not touch compliant). */
function _getTouchEventName(instance, eventName) {
var settings = instance.data('options');
if (!_isTouchDevice() && settings.emulateTouchEvents) {
switch (eventName) {
case 'touchstart' : return 'mousedown';
case 'touchend' : return 'mouseup';
case 'touchmove' : return 'mousemove';
}
}
return eventName;
}
/* Puts (set or replace) an item into the markup cache of the instance .*/
function _putMarkupCache(instance, key, value) {
var markup = instance.data('markup');
// Create cache if not found
if (!markup) {
markup ={};
instance.data('markup', markup);
}
// Store
markup[key] = value;
}
/* Retieves an item from the markup cache. */
function _getMarkupCache(instance, key) {
var markup = instance.data('markup');
if (markup) {
return markup[key];
} else {
return null;
}
}
/* Puts (set or replace) an item into tracking data. */
function _putTrackingData(instance, key, value) {
var tracking = instance.data('tracking');
// Create array if not found
if (!tracking) {
tracking = {};
instance.data('tracking', tracking);
}
// Store
tracking[key] = value;
}
/* Retieves an item from tracking data. */
function _getTrackingData(instance, key) {
var tracking = instance.data('tracking');
if (tracking) {
return tracking[key];
} else {
return null;
}
}
/* Resets tracking data. */
function _resetTouchTrackingData(instance) {
_putTrackingData(instance, 'startTouchTime', null);
_putTrackingData(instance, 'startTouchY', null);
_putTrackingData(instance, 'previousTouchTime', null);
_putTrackingData(instance, 'previousTouchY', null);
_putTrackingData(instance, 'lastTouchTime', null);
_putTrackingData(instance, 'lastTouchY', null);
}
/* Makes element unselectable. */
function _makeUnselectable(element) {
element.attr('unselectable', 'on')
.css({
'-moz-user-select':'none',
'-webkit-user-select':'none',
'user-select':'none',
'-ms-user-select':'none'
})
.each(function() {
this.onselectstart = function() { return false; };
});
}
/* Fixes scrollTop value for container. */
function _fixContainerScrollTopBounds(instance, scrollTopValue) {
var settings = instance.data('options');
var pullHeaderHeight = _getPullHeaderHeight(instance);
if (settings.pull && (scrollTopValue < pullHeaderHeight)) {
return pullHeaderHeight;
} else {
return scrollTopValue;
}
}
/* Creates plugin markup */
function _createMarkup(instance) {
var settings = instance.data('options');
// Calculate initial heigth
var initialHeight = instance.height();
// Create content wrapper
var contentWrapper = $('<div class="scrollz-content-wrapper"/>');
// Create container
var container = $('<div class="scrollz-container"/>');
container.css('height', initialHeight);
container.css('overflow-x', 'hidden');
container.css('overflow-y', 'hidden');
if (settings.styleClass) {
container.addClass(settings.styleClass);
}
// Wrap container arround content wrapper
instance.wrap(container).wrap(contentWrapper);
instance.css('overflow-y', 'visible');
// Update references
contentWrapper = instance.parent();
container = contentWrapper.parent();
// Create scroll thumb (and hide it)
var scrollThumb = $('<div class="scrollz-thumb"></div>');
scrollThumb.css('position', 'absolute');
container.prepend(scrollThumb);
scrollThumb = container.find('.scrollz-thumb');
scrollThumb.hide();
// Remove height from content
instance.css('height', 'auto');
instance.css('min-height', initialHeight);
// Store generated markup refrerences into object data
_putMarkupCache(instance, 'contentWrapper', contentWrapper);
_putMarkupCache(instance, 'container', container);
_putMarkupCache(instance, 'scrollThumb', scrollThumb);
// Pull support setup
if (settings.pull) {
// Create pull header
var pullHeader = $(settings.pullHeaderHTML.initial);
pullHeader.addClass('scrollz-pull-header').addClass('initial');
// Add pull header
contentWrapper.prepend(pullHeader);
// Store pull header in markup cache
_putMarkupCache(instance, 'pullHeader', contentWrapper.children('.scrollz-pull-header'));
// Container height must be at least as high as the pull header
var pullHeaderHeight = _getPullHeaderHeight(instance);
if (initialHeight < pullHeaderHeight) {
container.css('height', pullHeaderHeight);
instance.css('min-height', pullHeaderHeight);
}
// Move container to hide header
container.scrollTop(pullHeaderHeight);
// Make container unselectable
_makeUnselectable(container);
}
}
/* Change pull header state. */
function _changePullHeaderState(instance, state) {
var settings = instance.data('options');
var contentWrapper = _getMarkupCache(instance, 'contentWrapper');
var pullHeader = contentWrapper.children('.scrollz-pull-header');
if (!pullHeader.hasClass(state)) {
pullHeader.replaceWith($(settings.pullHeaderHTML[state]).addClass('scrollz-pull-header').addClass(state));
}
// Update pull header in stored markup
_putMarkupCache(instance, 'pullHeader', contentWrapper.children('.scrollz-pull-header'));
// Store current state
instance.data('pullHeaderState', state);
}
/* Returns pull header state */
function _getPullHeaderState(instance) {
var state = instance.data('pullHeaderState');
if (!state) {
// If unknown : take 'initial' as default
state = 'initial';
}
return state;
}
/* Handles pull header */
function _handlePullHeader(instance) {
var settings = instance.data('options');
var container = _getMarkupCache(instance, 'container');
var pullHeaderHeight = _getPullHeaderHeight(instance);
if (settings.pull && (container.scrollTop() < pullHeaderHeight) && (_getPullHeaderState(instance) !== 'waiting')) {
// Handle pull to refresh (half of the header height)
if (container.scrollTop() < (pullHeaderHeight / 2)) {
// Trigger event
_changePullHeaderState(instance, 'waiting');
instance.trigger('pulled');
} else {
// Animate scroll : move back to initial position
container.animate({scrollTop: pullHeaderHeight}, 'fast');
}
}
}
/* Handles inertia. */
function _handleInertia(instance) {
var settings = instance.data('options');
var container = _getMarkupCache(instance, 'container');
// Compute speed and distance
var previousTouchY = _getTrackingData(instance, 'previousTouchY');
var lastTouchY = _getTrackingData(instance, 'lastTouchY');
var previousTouchTime = _getTrackingData(instance, 'previousTouchTime');
var duration = new Date() - previousTouchTime;
var distance = previousTouchY - lastTouchY;
var acceleration = Math.abs(distance / duration);
if (settings.inertia) {
var offset = Math.pow(acceleration, 2) * 750;
if (distance < 0) {
offset *= -1;
}
container.stop(true, true);
if (offset !== 0) {
container.animate({scrollTop: _fixContainerScrollTopBounds(instance, container.scrollTop() + offset)}, {duration: acceleration * 750, easing : 'easeOutCubic'});
}
}
}
/* Handles touchstart event. */
function _handleTouchStartEvent(event, instance) {
if (_getPullHeaderState(instance) !== 'waiting') {
var settings = instance.data('options');
var container = _getMarkupCache(instance, 'container');
// Stop animation (if any)
container.stop();
// Capture initial contact point
if (_isTouchDevice()) {
_putTrackingData(instance, 'startTouchY', event.originalEvent.targetTouches[0].screenY);
} else {
_putTrackingData(instance, 'startTouchY', event.screenY);
}
_putTrackingData(instance, 'startTouchTime', new Date());
_putTrackingData(instance, 'previousTouchY', _getTrackingData(instance, 'startTouchY'));
_putTrackingData(instance, 'previousTouchTime', _getTrackingData(instance, 'startTouchTime'));
_putTrackingData(instance, 'lastTouchY', _getTrackingData(instance, 'startTouchY'));
_putTrackingData(instance, 'lastTouchTime', _getTrackingData(instance, 'startTouchTime'));
_putTrackingData(instance, 'initialScrollPosition', container.scrollTop());
}
}
/* Handles touchmove event. */
function _handleTouchMoveEvent(event, instance) {
var container = _getMarkupCache(instance, 'container');
var startTouchY = _getTrackingData(instance, 'startTouchY');
var lastTouchY = _getTrackingData(instance, 'lastTouchY');
var lastTouchTime = _getTrackingData(instance, 'lastTouchTime');
var initialScrollPosition = _getTrackingData(instance, 'initialScrollPosition');
if (startTouchY) {
// Store last touch as previous touch
_putTrackingData(instance, 'previousTouchY', lastTouchY);
_putTrackingData(instance, 'previousTouchTime', lastTouchTime);
// Compute move and store last touch
var moveTo = 0;
if (_isTouchDevice()) {
moveTo = (startTouchY - event.originalEvent.changedTouches[0].screenY) + initialScrollPosition;
_putTrackingData(instance, 'lastTouchY',event.originalEvent.targetTouches[0].screenY);
} else {
moveTo = (startTouchY - event.screenY) + initialScrollPosition;
_putTrackingData(instance, 'lastTouchY', event.screenY);
}
_putTrackingData(instance, 'lastTouchTime', new Date());
// Move
container.scrollTop(moveTo);
}
}
/* Handles touchend event. */
function _handleTouchEndEvent(event, instance) {
var container = _getMarkupCache(instance, 'container');
var startTouchY = _getTrackingData(instance, 'startTouchY');
var previousTouchY = _getTrackingData(instance, 'previousTouchY');
var lastTouchY = _getTrackingData(instance, 'lastTouchY');
var initialScrollPosition = _getTrackingData(instance, 'initialScrollPosition');
if (!startTouchY) {
// Nothing to do : touch was already processed
return;
}
// Only prevent the default event from
// happening when the user has actually
// scrolled
if (startTouchY !== lastTouchY) {
event.preventDefault();
}
var pullHeaderHeight = _getPullHeaderHeight(instance);
if ((startTouchY < lastTouchY) && (container.scrollTop() < pullHeaderHeight)) {
_handlePullHeader(instance);
} else {
_handleInertia(instance);
}
// Reset data
_resetTouchTrackingData(instance);
}
/* Handles mousewheel event. */
function _handleMouseWheelEvent(event, instance) {
if (_getPullHeaderState(instance) !== 'waiting') {
var container = _getMarkupCache(instance, 'container');
var initialScrollPosition = _getTrackingData(instance, 'initialScrollPosition');
// Move
var offset = 0;
if (event.type === 'mousewheel') {
offset = event.originalEvent.screenY - (event.originalEvent.screenY + event.originalEvent.wheelDeltaY);
} else {
offset = event.originalEvent.screenY - (event.originalEvent.screenY + (event.originalEvent.detail * -1 * 3));
}
// Slowdown scroll if reaching the pull header
if ((container.scrollTop() + offset) < _getPullHeaderHeight(instance)) {
offset *= 0.05;
}
container.scrollTop(container.scrollTop() + offset);
}
}
/* Handles scroll event. */
function _handleScrollEvent(event, instance) {
var settings = instance.data('options');
var container = _getMarkupCache(instance, 'container');
var contentWrapper = _getMarkupCache(instance, 'contentWrapper');
var scrollThumb = _getMarkupCache(instance, 'scrollThumb');
// Bottom reached
if ((container.scrollTop() + container.height() + 1) >= container.get(0).scrollHeight) {
// Trigger event
instance.trigger('bottomreached');
}
// Refresh threshold reached (half of the header height)
if (settings.pull) {
if (container.scrollTop() < (_getPullHeaderHeight(instance) / 2)) {
_changePullHeaderState(instance, 'release');
} else {
_changePullHeaderState(instance, 'initial');
}
}
var pullHeaderHeight = _getPullHeaderHeight(instance);
if (container.scrollTop() >= pullHeaderHeight) {
// Fix the collapsing maring problem
var firstContentChild = instance.children().first();
var lastContentChild = instance.children().last();
if (firstContentChild && parseInt(firstContentChild.css('marginTop'), 10) >= 0) {
instance.css('padding-top', '1px');
}
if (lastContentChild && parseInt(lastContentChild.css('marginBottom'), 10) >= 0) {
instance.css('padding-bottom', '1px');
}
// Resize and move scroll thumb
scrollThumb.height((container.innerHeight() / contentWrapper.outerHeight(true) * (container.innerHeight() + pullHeaderHeight)) -(scrollThumb.outerHeight(true) - scrollThumb.outerHeight()));
scrollThumb.css('top', container.position().top + ((container.scrollTop() - pullHeaderHeight) / contentWrapper.outerHeight(true) * container.innerHeight()));
scrollThumb.css('left', container.position().left + container.width() - scrollThumb.outerWidth(true));
} else {
// Hide scroll thumb when on pull header
scrollThumb.hide();
}
}
/* Handles scrollstart event. */
function _handleScrollStartEvent(event, instance) {
var container = _getMarkupCache(instance, 'container');
var scrollThumb = _getMarkupCache(instance, 'scrollThumb');
// Show scroll thumb only if not on pull header
if (container.scrollTop() > _getPullHeaderHeight(instance)) {
scrollThumb.stop(true, true);
scrollThumb.fadeIn(500);
}
}
/* Handles scrollstop event. */
function _handleScrollStopEvent(event, instance) {
var scrollThumb = _getMarkupCache(instance, 'scrollThumb');
// Hide scroll thumb
scrollThumb.stop(true, true);
scrollThumb.delay(300).fadeOut(1000);
// Handle pull header for none touch devices (case of scroll with mouse wheel)
var startTouchY = _getTrackingData(instance, 'startTouchY');
if (!_isTouchDevice() && !startTouchY) {
_handlePullHeader(instance);
}
}
/* Checks if plugin was initialized */
function _isInitialized(instance) {
return instance.data('scrollzInitialized') != null;
}
// Public declaration
$.fn.scrollz = function(method) {
// Method calling logic
if (methods[method]) {
return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if (typeof method === 'object' || ! method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist');
return null;
}
};
// jQuery Mobile auto-enhancement
if ($.mobile) {
// Add listener on page create (before enhancement)
$(document).on("pagecreate", ":jqmData(role='page')", function() {
// Simple
$(":jqmData(scrollz='simple')").scrollz();
// Pull
$(":jqmData(scrollz='pull')").scrollz({
pull: true,
emulateTouchEvents: true
});
});
$(document).on("pageshow", ":jqmData(role='page')", function() {
// Force resize
$(window).resize();
});
$(window).bind('orientationchange', function(event) {
// Silent scroll for landscape mode: fixes a resize issue for iPhone
if (event.orientation === 'landscape') {
$.mobile.silentScroll(0);
}
});
// Resize listener : auto resize
$(window).resize(function() {
// Compute content heights (between header and footer, if any) visible and full
var headerHeight = 0;
$(".ui-page-active div.ui-header").each(function () {
headerHeight += $(this).outerHeight();
});
var footerHeight = 0;
$(".ui-page-active div.ui-footer").each(function () {
footerHeight += $(this).outerHeight();
});
var visibleContentHeight = (window.innerHeight ? window.innerHeight : $(window).height()) - (headerHeight ? headerHeight : 0) - (footerHeight ? footerHeight : 0);
$(":jqmData(scrollz='simple'), :jqmData(scrollz='pull')").scrollz('height', visibleContentHeight);
});
}
}(jQuery));