-
Notifications
You must be signed in to change notification settings - Fork 0
/
jquery.breakpoint.js
98 lines (75 loc) · 2.54 KB
/
jquery.breakpoint.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
96
97
98
(function ($) {
'use strict';
var breakpoints = [];
// Adds a breakpoint object with the following properties:
//
// condition = a function returning a boolean for whether this breakpoint should be active or not.
// first_enter = a function which will execute the FIRST TIME condition() is true.
// enter = a function which will execute everytime condition() turns from false to true.
// exit = a function which will execute everytime condition() turns from true to false.
$.breakpoint = function (breakpoint, options) {
options = $.extend(true, {}, $.breakpoint.defaults, options);
breakpoints.push(breakpoint);
// Activate event listeners when first breakpoint is added.
if (breakpoints.length === 1) {
$(window).on('resize orientationchange', function () {
checkAllBreakpoints();
});
}
checkSingleBreakpoint(breakpoint);
};
// Array of all added breakpoints.
$.breakpoint.breakpoints = breakpoints;
// Default options.
$.breakpoint.defaults = { /* none yet… */};
function checkActiveBreakpoint(breakpoint) {
if (!breakpoint.condition()) {
// We have left this breakpoint.
if (typeof breakpoint.exit === 'function') {
breakpoint.exit();
}
breakpoint.is_active = false;
}
}
function checkInactiveBreakpoint(breakpoint) {
if (breakpoint.condition()) {
// We have entered this breakpoint.
if (typeof breakpoint.first_enter === 'function') {
breakpoint.first_enter();
// As this function is only meant to run once, remove it now.
delete breakpoint.first_enter;
}
if (typeof breakpoint.enter === 'function') {
breakpoint.enter();
}
breakpoint.is_active = true;
}
}
function checkSingleBreakpoint(breakpoint) {
if (breakpoint.is_active) {
checkActiveBreakpoint(breakpoint);
}
else {
checkInactiveBreakpoint(breakpoint);
}
}
// Loop through all breakpoints and determine which ones are active.
function checkAllBreakpoints() {
// Build temporary array of active breakpoints
var active_breakpoints = $.grep(breakpoints, function (breakpoint) {
return breakpoint.is_active;
});
// Build temporary array of inactive breakpoints.
var inactive_breakpoints = $.grep(breakpoints, function (breakpoint) {
return !breakpoint.is_active;
});
// Check all active breakpoints first.
$.each(active_breakpoints, function (index, breakpoint) {
checkActiveBreakpoint(breakpoint);
});
// Check all inactive breakpoints.
$.each(inactive_breakpoints, function (index, breakpoint) {
checkInactiveBreakpoint(breakpoint);
});
}
}(jQuery));