forked from mathiasbynens/jquery-visibility
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jquery-visibility.js
48 lines (41 loc) · 1.51 KB
/
jquery-visibility.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
module.exports = function($) {
var prefix;
var property;
// In Opera, `'onfocusin' in document == true`, hence the extra `hasFocus` check to detect IE-like behavior
var eventName = 'onfocusin' in document && 'hasFocus' in document ? 'focusin focusout' : 'focus blur';
var prefixes = ['webkit', 'o', 'ms', 'moz', ''];
var $support = $.support;
var $event = $.event;
while ((prefix = prefixes.pop()) != undefined) {
property = (prefix ? prefix + 'H' : 'h') + 'idden';
if ($support.pageVisibility = typeof document[property] == 'boolean') {
eventName = prefix + 'visibilitychange';
break;
}
}
$(/blur$/.test(eventName) ? window : document).on(eventName, function(event) {
var type = event.type;
var originalEvent = event.originalEvent;
// Avoid errors from triggered native events for which `originalEvent` is
// not available.
if (!originalEvent) {
return;
}
var toElement = originalEvent.toElement;
// If it’s a `{focusin,focusout}` event (IE), `fromElement` and `toElement`
// should both be `null` or `undefined`; else, the page visibility hasn’t
// changed, but the user just clicked somewhere in the doc. In IE9, we need
// to check the `relatedTarget` property instead.
if (!/^focus./.test(type) || (
toElement == undefined &&
originalEvent.fromElement == undefined &&
originalEvent.relatedTarget == undefined
)) {
$event.trigger(
(
property && document[property] || /^(?:blur|focusout)$/.test(type) ? 'hide' : 'show'
) + '.visibility'
);
}
});
};