forked from imakewebthings/waypoints
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwaypoints.js
676 lines (561 loc) · 21.2 KB
/
waypoints.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
/*!
jQuery Waypoints - v1.1.7
Copyright (c) 2011-2012 Caleb Troughton
Dual licensed under the MIT license and GPL license.
https://github.com/imakewebthings/jquery-waypoints/blob/master/MIT-license.txt
https://github.com/imakewebthings/jquery-waypoints/blob/master/GPL-license.txt
*/
/*
Waypoints is a small jQuery plugin that makes it easy to execute a function
whenever you scroll to an element.
GitHub Repository: https://github.com/imakewebthings/jquery-waypoints
Documentation and Examples: http://imakewebthings.github.com/jquery-waypoints
Changelog:
v1.1.7
- Actually fix the post-load bug in Issue #28 from v1.1.3.
v1.1.6
- Fix potential memory leak by unbinding events on empty context elements.
v1.1.5
- Make plugin compatible with Browserify/RequireJS. (Thanks @cjroebuck)
v1.1.4
- Add handler option to give alternate binding method. (Issue #34)
v1.1.3
- Fix cases where waypoints are added post-load and should be triggered
immediately. (Issue #28)
v1.1.2
- Fixed error thrown by waypoints with triggerOnce option that were
triggered via resize refresh.
v1.1.1
- Fixed bug in initialization where all offsets were being calculated
as if set to 0 initially, causing unwarranted triggers during the
subsequent refresh.
- Added onlyOnScroll, an option for individual waypoints that disables
triggers due to an offset refresh that crosses the current scroll
point. (All credit to @knuton on this one.)
v1.1
- Moved the continuous option out of global settings and into the options
object for individual waypoints.
- Added the context option, which allows for using waypoints within any
scrollable element, not just the window.
v1.0.2
- Moved scroll and resize handler bindings out of load. Should play nicer
with async loaders like Head JS and LABjs.
- Fixed a 1px off error when using certain % offsets.
- Added unit tests.
v1.0.1
- Added $.waypoints('viewportHeight').
- Fixed iOS bug (using the new viewportHeight method).
- Added offset function alias: 'bottom-in-view'.
v1.0
- Initial release.
Support:
- jQuery versions 1.4.3+
- IE6+, FF3+, Chrome 6+, Safari 4+, Opera 11
- Other versions and browsers may work, these are just the ones I've looked at.
*/
(function($, wp, wps, window, undefined){
'$:nomunge';
var $w = $(window),
// Keeping common strings as variables = better minification
eventName = 'waypoint.reached',
/*
For the waypoint and direction passed in, trigger the waypoint.reached
event and deal with the triggerOnce option.
*/
triggerWaypoint = function(way, dir) {
way.element.trigger(eventName, dir);
if (way.options.triggerOnce) {
way.element[wp]('destroy');
}
},
/*
Given a jQuery element and Context, returns the index of that element in the waypoints
array. Returns the index, or -1 if the element is not a waypoint.
*/
waypointIndex = function(el, context) {
if (!context) return -1;
var i = context.waypoints.length - 1;
while (i >= 0 && context.waypoints[i].element[0] !== el[0]) {
i -= 1;
}
return i;
},
// Private list of all elements used as scrolling contexts for waypoints.
contexts = [],
/*
Context Class - represents a scrolling context. Properties include:
element: jQuery object containing a single HTML element.
waypoints: Array of waypoints operating under this scroll context.
oldScroll: Keeps the previous scroll position to determine scroll direction.
didScroll: Flag used in scrolling the context's scroll event.
didResize: Flag used in scrolling the context's resize event.
doScroll: Function that checks for crossed waypoints. Called from throttler.
*/
Context = function(context) {
$.extend(this, {
element: $(context),
oldScroll: 0,
/*
List of all elements that have been registered as waypoints.
Each object in the array contains:
element: jQuery object containing a single HTML element.
offset: The window scroll offset, in px, that triggers the waypoint event.
options: Options object that was passed to the waypoint fn function.
*/
'waypoints': [],
didScroll: false,
didResize: false,
doScroll: $.proxy(function() {
var newScroll = this.element.scrollTop(),
// Are we scrolling up or down? Used for direction argument in callback.
isDown = newScroll > this.oldScroll,
that = this,
// Get a list of all waypoints that were crossed since last scroll move.
pointsHit = $.grep(this.waypoints, function(el, i) {
return isDown ?
(el.offset > that.oldScroll && el.offset <= newScroll) :
(el.offset <= that.oldScroll && el.offset > newScroll);
}),
len = pointsHit.length;
// iOS adjustment
if (!this.oldScroll || !newScroll) {
$[wps]('refresh');
}
// Done with scroll comparisons, store new scroll before ejection
this.oldScroll = newScroll;
// No waypoints crossed? Eject.
if (!len) return;
// If several waypoints triggered, need to do so in reverse order going up
if (!isDown) pointsHit.reverse();
/*
One scroll move may cross several waypoints. If the waypoint's continuous
option is true it should fire even if it isn't the last waypoint. If false,
it will only fire if it's the last one.
*/
$.each(pointsHit, function(i, point) {
if (point.options.continuous || i === len - 1) {
triggerWaypoint(point, [isDown ? 'down' : 'up']);
}
});
}, this)
});
// Setup scroll and resize handlers. Throttled at the settings-defined rate limits.
$(context).bind('scroll.waypoints', $.proxy(function() {
if (!this.didScroll) {
this.didScroll = true;
window.setTimeout($.proxy(function() {
this.doScroll();
this.didScroll = false;
}, this), $[wps].settings.scrollThrottle);
}
}, this)).bind('resize.waypoints', $.proxy(function() {
if (!this.didResize) {
this.didResize = true;
window.setTimeout($.proxy(function() {
$[wps]('refresh');
this.didResize = false;
}, this), $[wps].settings.resizeThrottle);
}
}, this));
$w.load($.proxy(function() {
/*
Fire a scroll check, should the page be loaded at a non-zero scroll value,
as with a fragment id link or a page refresh.
*/
this.doScroll();
}, this));
},
/* Returns a Context object from the contexts array, given the raw HTML element
for that context. */
getContextByElement = function(element) {
var found = null;
$.each(contexts, function(i, c) {
if (c.element[0] === element) {
found = c;
return false;
}
});
return found;
},
// Methods exposed to the effin' object
methods = {
/*
jQuery.fn.waypoint([handler], [options])
handler
function, optional
A callback function called when the user scrolls past the element.
The function signature is function(event, direction) where event is
a standard jQuery Event Object and direction is a string, either 'down'
or 'up' indicating which direction the user is scrolling.
options
object, optional
A map of options to apply to this set of waypoints, including where on
the browser window the waypoint is triggered. For a full list of
options and their defaults, see $.fn.waypoint.defaults.
This is how you register an element as a waypoint. When the user scrolls past
that element it triggers waypoint.reached, a custom event. Since the
parameters for creating a waypoint are optional, we have a few different
possible signatures. Let’s look at each of them.
someElements.waypoint();
Calling .waypoint with no parameters will register the elements as waypoints
using the default options. The elements will fire the waypoint.reached event,
but calling it in this way does not bind any handler to the event. You can
bind to the event yourself, as with any other event, like so:
someElements.bind('waypoint.reached', function(event, direction) {
// make it rain
});
You will usually want to create a waypoint and immediately bind a function to
waypoint.reached, and can do so by passing a handler as the first argument to
.waypoint:
someElements.waypoint(function(event, direction) {
if (direction === 'down') {
// do this on the way down
}
else {
// do this on the way back up through the waypoint
}
});
This will still use the default options, which will trigger the waypoint when
the top of the element hits the top of the window. We can pass .waypoint an
options object to customize things:
someElements.waypoint(function(event, direction) {
// do something amazing
}, {
offset: '50%' // middle of the page
});
You can also pass just an options object.
someElements.waypoint({
offset: 100 // 100px from the top
});
This behaves like .waypoint(), in that it registers the elements as waypoints
but binds no event handlers.
Calling .waypoint on an existing waypoint will extend the previous options.
If the call includes a handler, it will be bound to waypoint.reached without
unbinding any other handlers.
*/
init: function(f, options) {
// Register each element as a waypoint, add to array.
this.each(function() {
var cElement = $.fn[wp].defaults.context,
context,
$this = $(this);
// Default window context or a specific element?
if (options && options.context) {
cElement = options.context;
}
// Find the closest element that matches the context
if (!$.isWindow(cElement)) {
cElement = $this.closest(cElement)[0];
}
context = getContextByElement(cElement);
// Not a context yet? Create and push.
if (!context) {
context = new Context(cElement);
contexts.push(context);
}
// Extend default and preexisting options
var ndx = waypointIndex($this, context),
base = ndx < 0 ? $.fn[wp].defaults : context.waypoints[ndx].options,
opts = $.extend({}, base, options);
// Offset aliases
opts.offset = opts.offset === "bottom-in-view" ?
function() {
var cHeight = $.isWindow(cElement) ? $[wps]('viewportHeight')
: $(cElement).height();
return cHeight - $(this).outerHeight();
} : opts.offset;
// Update, or create new waypoint
if (ndx < 0) {
context.waypoints.push({
'element': $this,
'offset': null,
'options': opts
});
}
else {
context.waypoints[ndx].options = opts;
}
// Bind the function if it was passed in.
if (f) {
$this.bind(eventName, f);
}
// Bind the function in the handler option if it exists.
if (options && options.handler) {
$this.bind(eventName, options.handler);
}
});
// Need to re-sort+refresh the waypoints array after new elements are added.
$[wps]('refresh');
return this;
},
/*
jQuery.fn.waypoint('remove')
Passing the string 'remove' to .waypoint unregisters the elements as waypoints
and wipes any custom options, but leaves the waypoint.reached events bound.
Calling .waypoint again in the future would reregister the waypoint and the old
handlers would continue to work.
*/
remove: function() {
return this.each(function(i, el) {
var $el = $(el);
$.each(contexts, function(i, c) {
var ndx = waypointIndex($el, c);
if (ndx >= 0) {
c.waypoints.splice(ndx, 1);
if (!c.waypoints.length) {
c.element.unbind('scroll.waypoints resize.waypoints');
contexts.splice(i, 1);
}
}
});
});
},
/*
jQuery.fn.waypoint('destroy')
Passing the string 'destroy' to .waypoint will unbind all waypoint.reached
event handlers on those elements and unregisters them as waypoints.
*/
destroy: function() {
return this.unbind(eventName)[wp]('remove');
}
},
/*
Methods used by the jQuery object extension.
*/
jQMethods = {
/*
jQuery.waypoints('refresh')
This will force a recalculation of each waypoint’s trigger point based on
its offset option and context. This is called automatically whenever the window
(or other defined context) is resized, new waypoints are added, or a waypoint’s
options are modified. If your project is changing the DOM or page layout without
doing one of these things, you may want to manually call this refresh.
*/
refresh: function() {
$.each(contexts, function(i, c) {
var isWin = $.isWindow(c.element[0]),
contextOffset = isWin ? 0 : c.element.offset().top,
contextHeight = isWin ? $[wps]('viewportHeight') : c.element.height(),
contextScroll = isWin ? 0 : c.element.scrollTop();
$.each(c.waypoints, function(j, o) {
/* $.each isn't safe from element removal due to triggerOnce.
Should rewrite the loop but this is way easier. */
if (!o) return;
// Adjustment is just the offset if it's a px value
var adjustment = o.options.offset,
oldOffset = o.offset;
// Set adjustment to the return value if offset is a function.
if (typeof o.options.offset === "function") {
adjustment = o.options.offset.apply(o.element);
}
// Calculate the adjustment if offset is a percentage.
else if (typeof o.options.offset === "string") {
var amount = parseFloat(o.options.offset);
adjustment = o.options.offset.indexOf("%") ?
Math.ceil(contextHeight * (amount / 100)) : amount;
}
/*
Set the element offset to the window scroll offset, less
all our adjustments.
*/
o.offset = o.element.offset().top - contextOffset
+ contextScroll - adjustment;
/*
An element offset change across the current scroll point triggers
the event, just as if we scrolled past it unless prevented by an
optional flag.
*/
if (o.options.onlyOnScroll) return;
if (oldOffset !== null && c.oldScroll > oldOffset && c.oldScroll <= o.offset) {
triggerWaypoint(o, ['up']);
}
else if (oldOffset !== null && c.oldScroll < oldOffset && c.oldScroll >= o.offset) {
triggerWaypoint(o, ['down']);
}
/* For new waypoints added after load, check that down should have
already been triggered */
else if (!oldOffset && c.element.scrollTop() > o.offset) {
triggerWaypoint(o, ['down']);
}
});
// Keep waypoints sorted by offset value.
c.waypoints.sort(function(a, b) {
return a.offset - b.offset;
});
});
},
/*
jQuery.waypoints('viewportHeight')
This will return the height of the viewport, adjusting for inconsistencies
that come with calling $(window).height() in iOS. Recommended for use
within any offset functions.
*/
viewportHeight: function() {
return (window.innerHeight ? window.innerHeight : $w.height());
},
/*
jQuery.waypoints()
This will return a jQuery object with a collection of all registered waypoint
elements.
$('.post').waypoint();
$('.ad-unit').waypoint(function(event, direction) {
// Passed an ad unit
});
console.log($.waypoints());
The example above would log a jQuery object containing all .post and .ad-unit
elements.
*/
aggregate: function() {
var points = $();
$.each(contexts, function(i, c) {
$.each(c.waypoints, function(i, e) {
points = points.add(e.element);
});
});
return points;
}
};
/*
fn extension. Delegates to appropriate method.
*/
$.fn[wp] = function(method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
}
else if (typeof method === "function" || !method) {
return methods.init.apply(this, arguments);
}
else if (typeof method === "object") {
return methods.init.apply(this, [null, method]);
}
else {
$.error( 'Method ' + method + ' does not exist on jQuery ' + wp );
}
};
/*
The default options object that is extended when calling .waypoint. It has the
following properties:
context
string | element | jQuery*
default: window
The context defines which scrollable element the waypoint belongs to and acts
within. The default, window, means the waypoint offset is calculated with relation
to the whole viewport. You can set this to another element to use the waypoints
within that element. Accepts a selector string, *but if you use jQuery 1.6+ it
also accepts a raw HTML element or jQuery object.
continuous
boolean
default: true
If true, and multiple waypoints are triggered in one scroll, this waypoint will
trigger even if it is not the last waypoint reached. If false, it will only
trigger if it is the last waypoint.
handler
function
default: undefined
An alternative way to bind functions to the waypoint, without using the function
as the first argument to the waypoint function.
offset
number | string | function
default: 0
Determines how far the top of the element must be from the top of the browser
window to trigger a waypoint. It can be a number, which is taken as a number
of pixels, a string representing a percentage of the viewport height, or a
function that will return a number of pixels.
onlyOnScroll
boolean
default: false
If true, this waypoint will not trigger if an offset change during a refresh
causes it to pass the current scroll point.
triggerOnce
boolean
default: false
If true, the waypoint will be destroyed when triggered.
An offset of 250 would trigger the waypoint when the top of the element is 250px
from the top of the viewport. Negative values for any offset work as you might
expect. A value of -100 would trigger the waypoint when the element is 100px above
the top of the window.
offset: '100%'
A string percentage will determine the pixel offset based on the height of the
window. When resizing the window, this offset will automatically be recalculated
without needing to call $.waypoints('refresh').
// The bottom of the element is in view
offset: function() {
return $.waypoints('viewportHeight') - $(this).outerHeight();
}
Offset can take a function, which must return a number of pixels from the top of
the window. The this value will always refer to the raw HTML element of the
waypoint. As with % values, functions are recalculated automatically when the
window resizes. For more on recalculating offsets, see $.waypoints('refresh').
An offset value of 'bottom-in-view' will act as an alias for the function in the
example above, as this is a common usage.
offset: 'bottom-in-view'
You can see this alias in use on the Scroll Analytics example page.
The triggerOnce flag, if true, will destroy the waypoint after the first trigger.
This is just a shortcut for calling .waypoint('destroy') within the waypoint
handler. This is useful in situations such as scroll analytics, where you only
want to record an event once for each page visit.
The context option lets you use Waypoints within an element other than the window.
You can define the context with a selector string and the waypoint will act within
the nearest ancestor that matches this selector.
$('.something-scrollable .waypoint').waypoint({
context: '.something-scrollable'
});
You can see this in action on the Dial Controls example.
The handler option gives authors an alternative way to bind functions when
creating a waypoint. In place of:
$('.item').waypoint(function(event, direction) {
// make things happen
});
You may instead write:
$('.item').waypoint({
handler: function(event, direction) {
// make things happen
}
});
*/
$.fn[wp].defaults = {
continuous: true,
offset: 0,
triggerOnce: false,
context: window
};
/*
jQuery object extension. Delegates to appropriate methods above.
*/
$[wps] = function(method) {
if (jQMethods[method]) {
return jQMethods[method].apply(this);
}
else {
return jQMethods['aggregate']();
}
};
/*
$.waypoints.settings
Settings object that determines some of the plugin’s behavior.
resizeThrottle
number
default: 200
For performance reasons, the refresh performed during resizes is
throttled. This value is the rate-limit in milliseconds between resize
refreshes. For more information on throttling, check out Ben Alman’s
throttle / debounce plugin.
http://benalman.com/projects/jquery-throttle-debounce-plugin/
scrollThrottle
number
default: 100
For performance reasons, checking for any crossed waypoints during a
scroll event is throttled. This value is the rate-limit in milliseconds
between scroll checks. For more information on throttling, check out Ben
Alman’s throttle / debounce plugin.
http://benalman.com/projects/jquery-throttle-debounce-plugin/
*/
$[wps].settings = {
resizeThrottle: 200,
scrollThrottle: 100
};
$w.load(function() {
// Calculate everything once on load.
$[wps]('refresh');
});
})(jQuery, 'waypoint', 'waypoints', window);