| 
 | 1 | +// Get the elements from the DOM  | 
 | 2 | +const birthdayInput = document.getElementById("birthday");  | 
 | 3 | +const calculateButton = document.getElementById("calculate");  | 
 | 4 | +const resultElement = document.getElementById("result");  | 
 | 5 | + | 
 | 6 | +// Add click event listener to the calculate button  | 
 | 7 | +calculateButton.addEventListener("click", calculateAge);  | 
 | 8 | + | 
 | 9 | +// Function to calculate the age  | 
 | 10 | + | 
 | 11 | +function calculateAge() {  | 
 | 12 | +  // Get the value from the input  | 
 | 13 | +  const birthday = birthdayInput.value;  | 
 | 14 | + | 
 | 15 | +  // Check if the value is empty  | 
 | 16 | +  if (birthday === "") {  | 
 | 17 | +    // If the value is empty, show an alert  | 
 | 18 | +    alert("Please enter your birthday");  | 
 | 19 | +  } else {  | 
 | 20 | +    // If the value is not empty, calculate the age  | 
 | 21 | +    const age = getAge(birthday);  | 
 | 22 | + | 
 | 23 | +    // Show the result  | 
 | 24 | +    resultElement.innerHTML = `Your age is ${age} ${  | 
 | 25 | +      age > 1 ? "years" : "year" // Check if the age is more than 1  | 
 | 26 | +    } old`;  | 
 | 27 | +  }  | 
 | 28 | +}  | 
 | 29 | + | 
 | 30 | +// Function to calculate the age  | 
 | 31 | +function getAge(birthDay) {  | 
 | 32 | +  // Get the current date  | 
 | 33 | +  const currentDate = new Date();  | 
 | 34 | + | 
 | 35 | +  // Get the birthday date  | 
 | 36 | +  const birthdayDate = new Date(birthDay);  | 
 | 37 | + | 
 | 38 | +  // Calculate the age  | 
 | 39 | +  const age = currentDate.getFullYear() - birthdayDate.getFullYear();  | 
 | 40 | + | 
 | 41 | +  const month = currentDate.getMonth() - birthdayDate.getMonth();  | 
 | 42 | +  if (  | 
 | 43 | +    month < 0 ||  | 
 | 44 | +    (month === 0 && currentDate.getDate() < birthdayDate.getDate())  | 
 | 45 | +  ) {  | 
 | 46 | +    age--;  | 
 | 47 | +  }  | 
 | 48 | + | 
 | 49 | +  // Return the age  | 
 | 50 | +  return age;  | 
 | 51 | +}  | 
0 commit comments