-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
32 lines (27 loc) · 1006 Bytes
/
index.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
const btnEl = document.getElementById("btn");
const birthdayEl = document.getElementById("birthday");
const resultEl = document.getElementById("result");
function calculateAge() {
const birthdayValue = birthdayEl.value;
console.log(birthdayValue);
if (birthdayValue === "") {
alert("Please enter your birthday")
} else {
const age = getAge(birthdayValue);
resultEl.innerText = `Your age is ${age} ${age > 1 ? "years" : "year"} old`
}
};
// calculate the age and also subtract it
function getAge (birthdayValue) {
const currentDate = new Date();
const birthdayDate = new Date(birthdayValue);
let age = currentDate.getFullYear() - birthdayDate.getFullYear();
const month = currentDate.getMonth() - birthdayDate.getMonth();
if (
month < 0 || (month === 0 && currentDate.getDate() < birthdayDate.getDate())
) {
age --;
}
return age;
};
btnEl.addEventListener("click", calculateAge);