-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjquery.scrollTrigger.js
126 lines (82 loc) · 2.78 KB
/
jquery.scrollTrigger.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
(function ($) {
$.fn.scrollTrigger = function (options) {
/* Options */
var options = $.extend({
customEvents: ''
}, options || {});
/* Instance */
var instance = {
version: '0.6',
triggered: false
};
/* Variables */
var element = $(this);
/* Check Offset */
if (options.offset === undefined && element.length > 0) {
options.offset = element.offset().top;
}
/* Throw Error if offset is undefined */
if (options.offset === undefined) {
throw new Error('scrollTrigger.js: please, define offset property in plugin initialization, or attach it to DOM element.');
}
/* Check Gap */
options.gap = !isNaN(parseInt(options.gap)) ? options.gap : 0;
function getOffset () {
var
value = options.offset instanceof Function ? options.offset() : parseInt(options.offset);
if (isNaN(parseInt(value))) {
throw new Error('scrollTrigger.js: offset value is NaN.');
}
return value - options.gap;
}
function runCallback (callback, offset, triggered) {
if (Object.prototype.toString.call(triggered) === "[object Boolean]") {
instance.triggered = triggered;
}
if (callback instanceof Function) {
callback(instance, offset, options);
}
if (options.once === true) {
unbindEvent();
}
}
function runCallbackManually (callback) {
return function (changeState) {
var offsetTop = $(window).scrollTop();
var state = Object.prototype.toString.call(changeState) === "[object Boolean]" ? changeState : undefined;
runCallback(callback, offsetTop, state);
}
}
/* Instance 'on' property */
if (options.on instanceof Function) {
instance.on = function (changeState) {
runCallbackManually(options.on)(changeState);
}
}
/* Instance 'off' property */
if (options.off instanceof Function) {
instance.off = function (changeState) {
runCallbackManually(options.off)(changeState);
}
}
function eventHandler () {
/* Get window scrolltop */
var offsetTop = $(window).scrollTop();
var offset = getOffset();
/* Runs callback on */
if (offsetTop > offset && instance.triggered === false) {
runCallback(options.on, offsetTop, true);
}
/* Runs callback off */
else if (offsetTop < offset && instance.triggered === true) {
runCallback(options.off, offsetTop, false);
}
}
function unbindEvent () {
$(document).off('ready touchmove scroll ' + options.customEvents, eventHandler);
}
/* Events bindings */
$(document).on('ready touchmove scroll ' + options.customEvents, eventHandler);
return instance;
}
})(jQuery);