forked from will-ashworth/jQueryIsInViewport
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathisInViewport.jquery.js
More file actions
83 lines (70 loc) · 2.1 KB
/
isInViewport.jquery.js
File metadata and controls
83 lines (70 loc) · 2.1 KB
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
/* ====================================================
* jQuery is in viewport.
*
* https://github.com/frontid/jQueryIsInViewport
* Marcelo Iván Tosco (capynet)
* Inspired on https://stackoverflow.com/a/40658647/1413049
* ==================================================== */
!function ($) {
'use strict';
const IsInViewport = function (el, cb, offset) {
this.$el = $(el);
this.cb = cb;
this.offset = offset;
this.previousIsInState = false;
// Make the first check
this.check();
// Start watching.
this.watch();
return this;
};
IsInViewport.prototype = {
/**
* Checks if the element is in.
*
* @returns {boolean}
*/
isIn: function () {
const _self = this;
const $win = $(window);
const elementTop = _self.$el.offset().top - _self.offset;
const elementBottom = elementTop + _self.$el.outerHeight();
const viewportTop = $win.scrollTop();
const viewportBottom = viewportTop + $win.height();
return elementBottom > viewportTop && elementTop < viewportBottom;
},
/**
* Launch a callback indicating when the element is in and when is out.
*/
watch: function () {
const self = this;
$(window).on('resize scroll', self.check.bind(self));
},
/**
* Checks if the element is on in the viewport.
*/
check: function () {
const self = this;
if (self.isIn() && self.previousIsInState === false) {
self.cb.call(self.$el, 'entered');
self.previousIsInState = true;
}
if (self.previousIsInState === true && !self.isIn()) {
self.cb.call(self.$el, 'leaved');
self.previousIsInState = false;
}
}
};
// jQuery plugin.
//-----------------------------------------------------------
$.fn.isInViewport = function (cb, offset) {
offset || (offset = 0);
return this.each(function () {
const $element = $(this);
const data = $element.data('isInViewport');
if (!data) {
$element.data('isInViewport', (new IsInViewport(this, cb, offset)));
}
})
}
}(window.jQuery);