forked from tuupola/jquery_viewport
-
Notifications
You must be signed in to change notification settings - Fork 9
/
jquery.viewport.js
95 lines (82 loc) · 2.9 KB
/
jquery.viewport.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
/*
* Viewport - jQuery selectors for finding elements in viewport
*
* Copyright (c) 2008-2009 Mika Tuupola
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/mit-license.php
*
* Project home:
* http://www.appelsiini.net/projects/viewport
*
*/
(function($) {
$.belowthefold = function(element, settings) {
var fold = $(window).height() + $(window).scrollTop();
return fold <= $(element).offset().top - settings.threshold;
};
$.abovethetop = function(element, settings) {
var top = $(window).scrollTop();
return top >= $(element).offset().top + $(element).height() - settings.threshold;
};
$.rightofscreen = function(element, settings) {
var fold = $(window).width() + $(window).scrollLeft();
return fold <= $(element).offset().left - settings.threshold;
};
$.leftofscreen = function(element, settings) {
var left = $(window).scrollLeft();
return left >= $(element).offset().left + $(element).width() - settings.threshold;
};
$.inviewport = function(element, settings) {
var $element = $(element);
var offset = $element.offset();
var $window = $(window);
var windowTop = $window.scrollTop();
var threshold = settings.threshold;
if (offset.top - threshold < windowTop) {
if (offset.top + $element.height() + threshold >= windowTop) {
// top edge below the window's top
} else {
return false;
}
} else {
if (offset.top - threshold <= windowTop + $window.height()) {
// bottom edge above the window's bottom
} else {
return false;
}
}
var windowLeft = $window.scrollLeft();
if (offset.left - threshold < windowLeft) {
if (offset.left + $element.width() + threshold >= windowLeft) {
// left edge be on the left side of the window's left edge
} else {
return false;
}
} else {
if (offset.left - threshold <= windowLeft + $window.width()) {
// right edge be on the right side of the window's right edge
} else {
return false;
}
}
return true;
};
$.extend($.expr[':'], {
"below-the-fold": function(a, i, m) {
return $.belowthefold(a, {threshold : 0});
},
"above-the-top": function(a, i, m) {
return $.abovethetop(a, {threshold : 0});
},
"left-of-screen": function(a, i, m) {
return $.leftofscreen(a, {threshold : 0});
},
"right-of-screen": function(a, i, m) {
return $.rightofscreen(a, {threshold : 0});
},
"in-viewport": function(a, i, m) {
return $.inviewport(a, {threshold : 0});
}
});
})(jQuery);