-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathinView.jquery.js
61 lines (54 loc) · 1.71 KB
/
inView.jquery.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
$.fn.isInView = function (threshold = 0) {
var elementTop = $(this).offset().top;
var elementBottom = elementTop + $(this).outerHeight();
var viewportTop = $(window).scrollTop();
var viewportBottom = viewportTop + $(window).height();
return elementBottom > viewportTop + threshold && elementTop < viewportBottom - threshold;
};
$.fn.isSeen = function (value = null) {
// fuction that returns whether element has been seen before (bool)
var getSeen = function (element) {
if (element.attr('data-seen') == 'true') {
return true;
} else {
return false;
}
}
var isSeen = getSeen($(this));
// if value is given, set new value
if (value !== null) {
if (value) {
$(this).attr('data-seen', 'true');
} else {
$(this).attr('data-seen', 'false');
}
}
// return bool
return isSeen;
}
$.fn.inView = function (options) {
// parsing options
var defaults = {
in: function () { },
out: function () { },
threshold: 0
};
var options = Object.assign(defaults, options);
// persistent variables
var element = $(this);
var inView = false; // state
// update function to check if in view and execute callbacks
function update() {
// check for change
var newState = element.isInView(options.threshold);
if (inView !== newState) {
inView = newState;
inView ? options.in(element.isSeen(true)) : options.out(element.isSeen()); // pass isSeen as first paramater
}
}
update(); // run on execution
// run on change
$(window).on('resize scroll', function () {
update();
});
};