This repository has been archived by the owner on Aug 5, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 83
/
orientation.js
70 lines (59 loc) · 2.19 KB
/
orientation.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
define(["./mobifyjs", "./phoenix"], function(Mobify, phoenix) {
var $ = Mobify.$;
if (!$) return;
phoenix.register('orientation');
// Android `orientation` support is broken.
var supportsOrientation = $.support.orientation =
'orientation' in window && 'onorientationchange' in window
&& !/android/i.test(navigator.userAgent)
// Returns 'landscape' or 'portrait' based on the current orientation.
, getOrientation = function() {
var docEl = document.documentElement;
return !!(supportsOrientation
// 0 in portrait, 1 in landscape
? orientation % 180
// false in portrait, true in landscape
: docEl.clientWidth > docEl.clientHeight)
? 'landscape'
: 'portrait';
}
// Some Android browsers (HTC Sensation) don't update widths immediately,
// so wait to trigger the event.
, prevWidth
, timeout
, ersatzOrientation = function() {
clearTimeout(timeout);
var width = document.documentElement.clientWidth;
if (width == prevWidth) {
return timeout = setTimeout(ersatzOrientation, 250);
}
prevWidth = width;
$(window).trigger('orientationchange');
dispatchListeners();
}
, lastOrientation = getOrientation()
, listeners = []
, dispatchListeners = function() {
var orientation = getOrientation(),
prev = lastOrientation;
if (orientation != lastOrientation) {
lastOrientation = orientation;
// We have this strange order and an extra variable
// to ensure that exception in a listener would not leave
// lastOrientation not updated
for (var i = 0, l = listeners.length; i < l; ++i) {
listeners[i](orientation, prev);
}
}
}
, evName = supportsOrientation ? "orientationchange" : "resize"
, handler = supportsOrientation ? dispatchListeners : ersatzOrientation
, ensureOrientationHandler = function() {
$(window).unbind(evName, handler).bind(evName, handler);
};
Mobify.orientation = function(fn) {
if (!fn) return getOrientation();
ensureOrientationHandler();
listeners.push(fn);
}
});