-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
81 lines (67 loc) · 2.33 KB
/
index.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
var getIntersectClientRects = require('intersect-client-rects')
var getElementClientRect = require('element-client-rect')
var getViewportPosition = require('viewport-position')
var elementInDocument = require('element-in-document')
var elementStyle = require('element-style')
if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
module.exports = elementVisible
} else {
if (typeof define === 'function' && define.amd) {
define([], function () {
return elementVisible
})
} else {
window.elementVisivle = elementVisible
}
}
// Returns true if it is a DOM element
function isElement (o) {
return typeof HTMLElement === 'object'
? o instanceof HTMLElement
: o && typeof o === 'object' && o !== null && o.nodeType === 1 && typeof o.nodeName === 'string'
}
/**
* Finding out if the element is visible `threshold * 100`% in the viewport
*
* @param element {HTMLElement}
* @param threshold {Number}
* @returns {boolean}
*/
function elementVisible (element, threshold) {
var currentNode = element
var viewportRect
var clientRect
var clientRectArea
var visibleClientRect
var visibleClientRectArea
var visibleRatio
// Default: 100%
threshold = +threshold || 1.0
if (!element || !isElement(element)) {
throw new Error('Element is mandatory')
}
var doc = element.ownerDocument
if (threshold <= 0) {
throw new Error('Threshold value must be greater than 0')
}
do {
// Return false if our element is invisible
if (elementStyle(currentNode, 'opacity') === '0' ||
elementStyle(currentNode, 'display') === 'none' ||
elementStyle(currentNode, 'visibility') === 'hidden') {
return false
}
} while ((currentNode = currentNode.parentNode) !== document && currentNode)
// If element is actually visible in the document,
if (elementInDocument(element, threshold)) {
clientRect = getElementClientRect(element)
viewportRect = getViewportPosition(doc.defaultView || doc.parentWindow)
visibleClientRect = getIntersectClientRects(clientRect, viewportRect)
clientRectArea = clientRect.width * clientRect.height
visibleClientRectArea = visibleClientRect.width * visibleClientRect.height
visibleRatio = +clientRectArea ? visibleClientRectArea / clientRectArea : 0
return visibleRatio >= threshold
}
// Otherwise
return false
}