-
Notifications
You must be signed in to change notification settings - Fork 78
/
your-life.js
164 lines (144 loc) · 5.66 KB
/
your-life.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
/**
* Interactive form and chart events / logic.
*/
(function () {
var yearEl = document.getElementById('year'),
monthEl = document.getElementById('month'),
dayEl = document.getElementById('day'),
unitboxEl = document.getElementById('unitbox'),
unitText = document.querySelector('.unitbox-label').textContent.toLowerCase(),
items = document.querySelectorAll('.chart li'),
itemCount,
COLOR = 'red',
KEY = {
UP: 38,
DOWN: 40
};
// Set listeners
unitboxEl.addEventListener('change', _handleUnitChange);
yearEl.addEventListener('input', _handleDateChange);
yearEl.addEventListener('keydown', _handleUpdown);
yearEl.addEventListener('blur', _unhideValidationStyles);
monthEl.addEventListener('change', _handleDateChange);
monthEl.addEventListener('keydown', _handleUpdown);
dayEl.addEventListener('input', _handleDateChange);
dayEl.addEventListener('blur', _unhideValidationStyles);
dayEl.addEventListener('keydown', _handleUpdown);
// Ensure the month is unselected by default.
monthEl.selectedIndex = -1;
// Load default values
_loadStoredValueOfDOB();
// Event Handlers
function _handleUnitChange(e) {
window.location = '' + e.currentTarget.value + '.html';
}
function _handleDateChange(e) {
// Save date of birth in local storage
localStorage.setItem("DOB", JSON.stringify({
month: monthEl.value,
year: yearEl.value,
day: dayEl.value
}));
if (_dateIsValid()) {
itemCount = calculateElapsedTime();
_repaintItems(itemCount);
} else {
_repaintItems(0);
}
}
function _handleUpdown(e) {
var newNum;
// A crossbrowser keycode option.
thisKey = e.keyCode || e.which;
if (e.target.checkValidity()) {
if (thisKey === KEY.UP) {
newNum = parseInt(e.target.value, 10);
e.target.value = newNum += 1;
// we call the date change function manually because the input event isn't
// triggered by arrow keys, or by manually setting the value, as we've done.
_handleDateChange();
} else if (thisKey === KEY.DOWN) {
newNum = parseInt(e.target.value, 10);
e.target.value = newNum -= 1;
_handleDateChange();
}
}
}
function _unhideValidationStyles(e) {
e.target.classList.add('touched');
}
function calculateElapsedTime() {
var currentDate = new Date(),
dateOfBirth = _getDateOfBirth(),
diff = currentDate.getTime() - dateOfBirth.getTime(),
elapsedTime;
switch (unitText) {
case 'weeks':
// Measuring weeks is tricky since our chart shows 52 weeks per year (for simplicity)
// when the actual number of weeks per year is 52.143. Attempting to calculate weeks
// with a diffing strategy will result in build-up over time. Instead, we'll add up
// 52 per elapsed full year, and only diff the weeks on the current partial year.
var elapsedYears = (new Date(diff).getUTCFullYear() - 1970);
var isThisYearsBirthdayPassed = (currentDate.getTime() > new Date(currentDate.getUTCFullYear(), monthEl.value, dayEl.value).getTime());
var birthdayYearOffset = isThisYearsBirthdayPassed ? 0 : 1;
var dateOfLastBirthday = new Date(currentDate.getUTCFullYear() - birthdayYearOffset, monthEl.value, dayEl.value);
var elapsedDaysSinceLastBirthday = Math.floor((currentDate.getTime() - dateOfLastBirthday.getTime()) / (1000 * 60 * 60 * 24));
var elapsedWeeks = (elapsedYears * 52) + Math.floor(elapsedDaysSinceLastBirthday / 7);
elapsedTime = elapsedWeeks;
break;
case 'months':
// Months are tricky, being variable length, so I opted for the average number
// of days in a month as a close-enough approximation (30.4375). This can make
// the chart look off by a day when you're right on the month threshold, but
// it's otherwise fairly accurate over long periods of time.
elapsedTime = Math.floor(diff / (1000 * 60 * 60 * 24 * 30.4375));
break;
case 'years':
// We can represent our millisecond diff as a year and subtract 1970 to
// end up with an accurate elapsed time. To see why, consider the following:
//
// 1. JavaScript's Date timestamp represents milliseconds since 1970. Thus,
// new Date(0).toUTCString() → 'Thu, 01 Jan 1970 00:00:00 GMT'
// 2. Picture the diff between today and tomorrow. It's a small number. A
// newly created date with that number would result in January 2 1970.
// 3. Thus, subtracting 1970 from that date gives us elapsed time. We use
// UTC because otherwise we'd need to offset "1970" by our timezone.
//
// See more details here: https://stackoverflow.com/a/24181701/1154642
elapsedTime = (new Date(diff).getUTCFullYear() - 1970);
break;
}
return elapsedTime;
}
function _dateIsValid() {
return monthEl.checkValidity() && dayEl.checkValidity() && yearEl.checkValidity();
}
function _getDateOfBirth() {
return new Date(yearEl.value, monthEl.value, dayEl.value);
}
function _repaintItems(number) {
for (var i = 0; i < items.length; i++) {
if (i < number) {
items[i].style.backgroundColor = COLOR;
} else {
items[i].style.backgroundColor = '';
}
}
}
function _loadStoredValueOfDOB() {
var DOB = JSON.parse(localStorage.getItem('DOB'));
if (!DOB) {
return;
}
if (DOB.month >= 0 && DOB.month < 12) {
monthEl.value = DOB.month
}
if (DOB.year) {
yearEl.value = DOB.year
}
if (DOB.day > 0 && DOB.day < 32) {
dayEl.value = DOB.day
}
_handleDateChange();
}
})();