-
Notifications
You must be signed in to change notification settings - Fork 45
/
smartscroll.js
538 lines (483 loc) · 17.9 KB
/
smartscroll.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
(function ($) { // eslint-disable-line func-names
/**
* CONSTANTS
*/
var MOUSE_EVENTS_STRING = 'mousewheel DOMMouseScroll wheel MozMousePixelScroll';
/**
* DEPENDENCIES
*/
// Register lethargy as a soft dependency
var lethargy;
if (typeof Lethargy !== 'undefined' && Lethargy !== null) {
lethargy = new Lethargy();
}
/**
* FUNCTIONS
*/
var getWindowTop = function () {
// jQuery uses only window.pageYOffset
// https://github.com/jquery/jquery/blob/29370190605ed5ddf5d0371c6ad886a4a4b5e0f9/src/offset.js#L184
return Math.max(
// Does not work for IE8 or below
// Alias for window.scrollY
// https://developer.mozilla.org/en-US/docs/Web/API/Window/pageYOffset
window.pageYOffset,
// Does not work for IE versions below Edge
// https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollY
//
// window.scrollY,
// Caters for quirks mode
// Deprecated in ES5 strict mode
// so for standards mode use document.documentElement.scrollTop instead
//
window.document.body.scrollTop,
// Caters for standards mode
// Should be the same as `window.pageYOffset`
window.document.documentElement.scrollTop
);
};
$.smartscroll = function smartscroll(overrides) { // eslint-disable-line no-param-reassign
/**
* OPTIONS
*/
// Replace defaults with user-specified options
// Properties that are `null` or `undefined` are ignored - https://api.jquery.com/jquery.extend/
var options = $.extend({}, $.smartscroll.defaults, overrides);
// If `options.sectionSelector` is not set, use `options.sectionClass`
if (!options.sectionSelector) {
options.sectionSelector = '.' + options.sectionClass;
}
// Invalidate eventEmitter if:
if (
// EventEmitter is not available / loaded,
typeof EventEmitter === 'undefined'
|| EventEmitter === null
// or the property of options.eventEmitter it is not an EventEmitter instance
|| (options.eventEmitter && options.eventEmitter.constructor !== EventEmitter)
) {
options.eventEmitter = null;
}
if (options.bindSwipe) {
// Adapted from http://stackoverflow.com/a/23230280/2317532,
// licensed under cc by-sa 3.0 with attribution required
// http://creativecommons.org/licenses/by-sa/3.0/
// (Might want to checkout http://stackoverflow.com/a/17567696/2317532 when time permits)
var xDown = null;
var yDown = null;
var handleTouchStart = function (event) {
var e = event.originalEvent || event;
xDown = e.touches[0].clientX;
yDown = e.touches[0].clientY;
};
var handleTouchMove = function (event) {
var e = event.originalEvent || event;
if (!xDown || !yDown) {
return;
}
var xUp = e.touches[0].clientX;
var yUp = e.touches[0].clientY;
var xDiff = xDown - xUp;
var yDiff = yDown - yUp;
if (Math.abs(xDiff) > Math.abs(yDiff)) {
if (xDiff > 0) {
options.eventEmitter.emitEvent('swipeLeft');
} else {
options.eventEmitter.emitEvent('swipeRight');
}
} else if (yDiff > 0) {
options.eventEmitter.emitEvent('swipeUp');
} else {
options.eventEmitter.emitEvent('swipeDown');
}
/* reset values */
xDown = null;
yDown = null;
};
}
/**
* RUNTIME VARIABLES
*/
// Whether jQuery is currently animating the scroll event
var isScrolling = false;
var sections = [];
var sectionWrapperTop;
var sectionWrapperBottom;
var validBreakPoint = false;
var belowBreakpoint = false;
var currentHash = window.location.hash;
// Store the current section wrapper method for later use
var sectionWrapper = $(options.sectionWrapperSelector + ':first');
/**
* FUNCTIONS
*/
// Check if the view is currently within the section wrapper
var sectionWrapperIsVisible = function () {
var windowTop = getWindowTop();
var windowBottom = windowTop + $(window).height();
// Only affect scrolling if within the sectionWrapper area
if (
windowBottom > sectionWrapperTop
&& windowTop <= sectionWrapperBottom
) {
return true;
}
return false;
};
// Update the values for `sections`
var calculateSectionBottoms = function () {
var tmpSections = [];
sectionWrapperTop = Math.round(
sectionWrapper.position().top
+ parseInt(sectionWrapper.css('paddingTop'), 10)
+ parseInt(sectionWrapper.css('borderTopWidth'), 10)
+ parseInt(sectionWrapper.css('marginTop'), 10));
// We use `height()` instead of `innerHeight()` or `outerHeight()`
// because we don't care about the padding in the sectionWrapper at the bottom
sectionWrapperBottom = Math.round(
sectionWrapperTop
+ sectionWrapper.height(), 10);
tmpSections.push(sectionWrapperTop);
$(options.sectionSelector).each(function (i, el) { // eslint-disable-line func-names
tmpSections.push(Math.round(
sectionWrapperTop
+ $(el).position().top // This will be relative to the sectionWrapper
+ $(el).outerHeight()
));
});
sections = tmpSections;
};
// Given the event object, determines if it's up or down,
// or invalid according to lethargy
var getScrollAction = function (e) {
// Always register the action with lethargy
var validScroll;
if (lethargy) {
validScroll = lethargy.check(e);
}
// Do nothing if it is already scrolling
if (!isScrolling) {
if (lethargy) {
if (validScroll === 1) {
return 'up';
} else if (validScroll === -1) {
return 'down';
}
} else if (e.originalEvent.wheelDelta > 0 || e.originalEvent.detail < 0) {
return 'up';
} else if (e.originalEvent.wheelDelta < 0 || e.originalEvent.detail > 0) {
return 'down';
}
}
return false;
};
// Checks the slide that is occupying the position specified
var getSectionIndexAt = function (position) {
for (var i = 0; i < sections.length; i += 1) {
if (position <= sections[i]) {
return i;
}
}
return sections.length;
};
// Change the hash (and also record history depending on options)
var autoHash = function () {
var newHash;
// If the middle of the screen is above the top of the section wrapper
// Set the hash to the header's hash
if ((getWindowTop() + ($(window).height() / 2)) < sectionWrapperTop) {
newHash = options.headerHash;
} else {
// Otherwise, get the index of the section at the middle of the screen
var slideIndex = getSectionIndexAt(getWindowTop() + ($(window).height() / 2));
if (slideIndex !== undefined) {
// And get the data-hash attribute of the section
newHash = $(options.sectionSelector + ':nth-of-type(' + slideIndex + ')').data('hash');
}
}
if (typeof newHash === 'undefined' || !(window.location.hash === ('#' + newHash))) {
if (typeof newHash === 'undefined') {
newHash = options.headerHash;
}
if (!options.keepHistory) {
window.location.replace(window.location.href.split('#')[0] + '#' + newHash);
} else {
window.location.hash = newHash;
}
}
};
// Animates the scroll to the pixel specified
// at the speed (milisseconds) specified
var scrollToPixel = function (pixel, speed) {
if (isScrolling) {
return;
}
isScrolling = true;
$('body,html').stop(true, true).animate({
scrollTop: pixel,
}, speed, function () { // eslint-disable-line func-names
isScrolling = false;
if (options.eventEmitter) {
var windowTop = getWindowTop();
var sectionIndexAtWindowMiddle = getSectionIndexAt(windowTop + ($(window).height() / 2));
options.eventEmitter.emitEvent('scrollEnd', [sectionIndexAtWindowMiddle]);
}
});
};
// Make this public
this.scroll = function scroll(down) {
if (sections) {
var windowTop = getWindowTop();
var sectionIndexAtWindowMiddle;
if (options.eventEmitter) {
sectionIndexAtWindowMiddle = getSectionIndexAt(windowTop + ($(window).height() / 2));
var nextSlideNumber = down ? (
sectionIndexAtWindowMiddle + 1
) : (
sectionIndexAtWindowMiddle - 1
);
options.eventEmitter.emitEvent('scrollStart', [nextSlideNumber]);
}
for (var i = 0; i < sections.length; i += 1) {
if (windowTop < sections[i]) {
if (down) {
scrollToPixel(sections[i], options.animationSpeed);
} else {
scrollToPixel(sections[i - 1] - $(window).height(), options.animationSpeed);
}
if (options.eventEmitter) {
options.eventEmitter.emitEvent('scrollEnd', [sectionIndexAtWindowMiddle]);
}
return false;
}
}
}
return undefined;
};
// Bind scroll events and perform scrolljacking
var bindScroll = function () {
$(window).bind(MOUSE_EVENTS_STRING, function (e) { // eslint-disable-line func-names
var scrollAction = getScrollAction(e);
if (options.dynamicHeight) {
calculateSectionBottoms();
}
var windowTop = getWindowTop();
var windowBottom = windowTop + $(window).height();
// Only affect scrolling if within the sectionWrapper area
if (
windowBottom > sectionWrapperTop
&& windowTop <= sectionWrapperBottom
) {
// Only hijack the scroll when windowTop and windowBottom are touching different slides
// `!==` instead of `<` caters for when `getSectionIndexAtWindowBottom` is `undefined`
// (at the end of the area)
var sectionIndexAtWindowTop = getSectionIndexAt(windowTop);
var sectionIndexAtWindowMiddle = getSectionIndexAt(windowTop + ($(window).height() / 2));
var sectionIndexAtWindowBottom = getSectionIndexAt(windowBottom);
if (sectionIndexAtWindowTop !== sectionIndexAtWindowBottom
|| !options.innerSectionScroll) {
e.preventDefault();
e.stopPropagation();
if (scrollAction) {
if (scrollAction === 'up') {
if (options.toptotop) {
scrollToPixel(
sections[sectionIndexAtWindowMiddle - 2] + 1
, options.animationSpeed
);
} else {
scrollToPixel(
sections[sectionIndexAtWindowMiddle - 1] - $(window).height()
, options.animationSpeed
);
}
if (options.eventEmitter) {
options.eventEmitter.emitEvent('scrollStart', [sectionIndexAtWindowMiddle - 1]);
}
} else if (scrollAction === 'down') {
scrollToPixel(sections[sectionIndexAtWindowMiddle] + 1, options.animationSpeed);
if (options.eventEmitter) {
options.eventEmitter.emitEvent('scrollStart', [sectionIndexAtWindowMiddle + 1]);
}
}
}
}
}
});
};
// Remove all functions bound to mouse events
var unbindScroll = function () {
$(window).unbind(MOUSE_EVENTS_STRING);
};
/**
* INITIAL SETUP
*/
sectionWrapper.css({
position: 'relative',
});
// Need to wait until content and CSS has been parsed
// So the height is accurate
setTimeout(function () { // eslint-disable-line func-names
calculateSectionBottoms();
// autoHash
if (options.autoHash) {
if (options.eventEmitter !== null && !options.hashContinuousUpdate) {
options.eventEmitter.addListener('scrollEnd', autoHash);
} else {
// Fallback with binding scroll events.
// Many scroll events are fired and so is very resource-intensive
$(window).bind('scroll', autoHash);
}
}
// Scroll to hash
if (options.initialScroll && currentHash.length > 0) {
// Remove the '#' from the hash and use jQuery to check
// if an element exists with that hash in the 'data-hash' attribute
var matchedObject = $('[data-hash="' + currentHash.substr(1) + '"]');
// If there is a matched element, scroll to the first element at time 0 (immediately)
if (matchedObject.length > 0) {
scrollToPixel(matchedObject[0].offsetTop + sectionWrapperTop, 0);
}
}
}, 50);
$(window).bind('resize', calculateSectionBottoms);
// Breakpoint
// If options.breakpoint is a valid value,
// set this.validBreakPoint to true
if (
options.breakpoint !== null
&& options.breakpoint === parseInt(options.breakpoint, 10)
&& options.breakpoint > 0
) {
validBreakPoint = true;
}
// Mode
// If the mode is set to vp (viewpoint),
// make the height of each section the same as the viewport
if (options.mode === 'vp') {
// IE8 does not support viewport
// http://caniuse.com/#feat=viewport-units
if (options.ie8) {
var resizeToVP = function () {
$(options.sectionSelector).css({
height: $(window).height(),
});
};
// Initial resizing on load
resizeToVP();
// Run resizeToVP whenever the window resizes
$(window).bind('resize', resizeToVP);
} else {
// Use viewport to avoid binding to resize events
$(options.sectionSelector).css({
height: '100vh',
});
}
}
// Scrolljacking
if (options.sectionScroll) {
// If the breakpoint option is set
if (validBreakPoint) {
// Run the following whenever the window is resized
$(window).bind('resize', function () { // eslint-disable-line func-names
// If the window width is below the breakpoint,
// Unbind scroll
if ($(window).width() < options.breakpoint) {
// Only unbind once (minimize resource usage)
if (!belowBreakpoint) {
unbindScroll();
// Set belowBreakpoint to true to prevent further unbinding events
belowBreakpoint = true;
return false;
}
} else if (belowBreakpoint) {
// If the screen width is currently equal to or above the breakpoint
// Bind scroll only if it's not bound already
bindScroll();
belowBreakpoint = false;
}
return undefined;
});
}
bindScroll();
}
if (options.bindSwipe) {
$(window).on('touchstart', handleTouchStart); // eslint-disable-line block-scoped-var
$(window).on('touchmove', handleTouchMove); // eslint-disable-line block-scoped-var
}
if (options.bindKeyboard) {
var handleKeydown = function (event) {
var e = event.originalEvent || event;
if (options.dynamicHeight) {
calculateSectionBottoms();
}
var windowTop = getWindowTop();
var windowBottom = windowTop + $(window).height();
// Only affect scrolling if within the sectionWrapper area
if (sectionWrapperIsVisible()) {
// Only hijack the scroll when windowTop and windowBottom are touching different slides
// `!==` instead of `<` caters for when `getSectionIndexAtWindowBottom` is `undefined`
// (at the end of the area)
var sectionIndexAtWindowTop = getSectionIndexAt(windowTop);
var sectionIndexAtWindowMiddle = getSectionIndexAt(windowTop + ($(window).height() / 2));
var sectionIndexAtWindowBottom = getSectionIndexAt(windowBottom);
if (sectionIndexAtWindowTop !== sectionIndexAtWindowBottom
|| !options.innerSectionScroll) {
switch (e.which) {
// up arrow
case 38:
e.preventDefault();
e.stopPropagation();
if (options.toptotop) {
scrollToPixel(
sections[sectionIndexAtWindowMiddle - 2] + 1
, options.animationSpeed);
} else {
scrollToPixel(
sections[sectionIndexAtWindowMiddle - 1] - $(window).height()
, options.animationSpeed);
}
if (options.eventEmitter) {
options.eventEmitter.emitEvent('scrollStart', [sectionIndexAtWindowMiddle - 1]);
}
break;
// down arrow
case 40:
e.preventDefault();
e.stopPropagation();
scrollToPixel(sections[sectionIndexAtWindowMiddle] + 1, options.animationSpeed);
if (options.eventEmitter) {
options.eventEmitter.emitEvent('scrollStart', [sectionIndexAtWindowMiddle + 1]);
}
break;
default:
}
}
}
};
$(window).on('keydown', handleKeydown);
}
return this;
};
// Set default options
$.smartscroll.defaults = { // eslint-disable-line no-param-reassign
animationSpeed: 700,
autoHash: true,
breakpoint: null,
initialScroll: true,
headerHash: 'header',
keepHistory: false,
mode: 'vp', // "vp", "set"
sectionClass: 'section',
sectionSelector: null,
sectionScroll: true,
sectionWrapperSelector: '.section-wrapper',
eventEmitter: null,
dynamicHeight: false,
ie8: false,
hashContinuousUpdate: true,
innerSectionScroll: true,
toptotop: false,
bindSwipe: true,
bindKeyboard: true,
};
}(jQuery));