-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscript.js
More file actions
32 lines (26 loc) · 909 Bytes
/
script.js
File metadata and controls
32 lines (26 loc) · 909 Bytes
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
const dob = document.getElementById("dob");
const calculate = document.getElementById("calculate");
const output = document.getElementById("output");
const calculateAge = () => {
const birthdayValue = dob.value;
if(birthdayValue === "") {
alert("Please select your birthday")
} else {
const age = getAge(birthdayValue);
output.innerText = `Your age is ${age} ${age > 1 ? "years" : "year"} old`
}
};
const 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;
}
calculate.addEventListener("click", calculateAge);