tilde.town/age.js

119 lines
3.4 KiB
JavaScript

var page = document.getElementById('main');
var birthday = new Date("1990-07-25T21:45:00");
var secsPer = {};
secsPer.second = 1;
secsPer.minute = 60;
secsPer.hour = secsPer.minute * 60;
secsPer.day = secsPer.hour * 24;
secsPer.week = secsPer.day * 7;
secsPer.year = secsPer.day * 365.2425;
secsPer.month = secsPer.year / 12;
function cumDiff(t1, t2) {
// x years, x weeks, x days, x hours, x minutes, x seconds
let diff = Math.abs(t2 - t1);
let seconds = diff / 1000;
let counts = {
'year': 0,
'week': 0,
'day': 0,
'hour': 0,
'minute': 0,
'second': 0
};
for (let count in counts) {
while (seconds >= secsPer[count]) {
counts[count] += 1;
seconds -= secsPer[count];
}
}
return counts;
}
function init() {
page.innerHTML = "";
var title = document.createElement("h1");
title.textContent = "How old am I?";
page.appendChild(title);
var cumAgeP = document.createElement('p');
cumAgeP.setAttribute('id', 'cumAge');
page.appendChild(cumAgeP);
var countdownTitle = document.createElement("h2");
countdownTitle.textContent = "How long til my next birthday?";
page.appendChild(countdownTitle);
var bdccP = document.createElement('p');
bdccP.setAttribute('id', 'bdcc');
page.appendChild(bdccP);
update();
}
function updateCumAge(t, el) {
var cumAge = document.createElement("p");
cumAge.setAttribute('id', 'cumAge');
cumAge.setAttribute('class', 'cumulative');
var cumAgeDiff = cumDiff(t, birthday);
for (let count in cumAgeDiff) {
if (cumAgeDiff[count] > 0) {
let dat = document.createElement("span");
dat.setAttribute('class', 'age');
dat.textContent = cumAgeDiff[count];
let postCount = '';
if (cumAgeDiff[count] > 1) { postCount += 's'; }
let str = document.createElement('span');
str.setAttribute('class', 'desc');
str.textContent = " "+count+postCount;
cumAge.appendChild(dat);
cumAge.appendChild(str);
}
}
el.replaceWith(cumAge);
}
function updateBdayCumCountdown(t, el) {
var bdcc = document.createElement("t");
bdcc.setAttribute('id', 'bdcc');
bdcc.setAttribute('class', 'cumulative');
let yearAdjust = 0;
if (t.getMonth() > birthday.getMonth()
|| (t.getMonth() == birthday.getMonth()
&& t.getDate() >= birthday.getDate())) {
yearAdjust = 1;
}
var nextBirthday = new Date(
t.getFullYear() + yearAdjust,
birthday.getMonth(),
birthday.getDate());
bdccDiff = cumDiff(t, nextBirthday);
for (let count in bdccDiff) {
if (bdccDiff[count] > 0) {
let dat = document.createElement("span");
dat.setAttribute('class', 'countdown');
dat.textContent = bdccDiff[count];
let postCount = '';
if (bdccDiff[count] > 1) { postCount += 's'; }
if (count !== 'second') { postCount += ', '; }
let str = document.createTextNode(" "+count+postCount);
bdcc.appendChild(dat);
bdcc.appendChild(str);
}
}
el.replaceWith(bdcc);
}
function update() {
now = new Date();
updateCumAge(now, document.getElementById('cumAge'));
updateBdayCumCountdown(now, document.getElementById('bdcc'));
}