You are currently viewing Age Calculator App in HTML, CSS , Javascript

Age Calculator App in HTML, CSS , Javascript

In this blog we will learn how to make a age calculator app in HTML , CSS and Javascript. It is beginner friendly for frontend web developers newby with source code

Age calculator app in Html css and javascript

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Age Calculator</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>

    <div class="container">
        <h1>Age Calculator</h1>

        <label for="dob">Enter your Date of Birth:</label>
        <input type="date" id="dob" required>

        <button onclick="calculateAge()">Calculate Age</button>

        <p id="ageResult"></p>
    </div>

    <script src="script.js"></script>
</body>
</html>

styles.css

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    font-family: Arial, sans-serif;
    background-color: #f4f4f9;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
}

.container {
    background-color: #fff;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    width: 100%;
    max-width: 400px;
    text-align: center;
}

h1 {
    color: #333;
    margin-bottom: 20px;
}

label {
    display: block;
    font-size: 1rem;
    margin-bottom: 8px;
    color: #555;
}

input {
    width: 100%;
    padding: 10px;
    margin-bottom: 20px;
    border: 1px solid #ddd;
    border-radius: 4px;
    font-size: 1rem;
    box-sizing: border-box;
}

button {
    padding: 10px 20px;
    background-color: #4CAF50;
    color: white;
    border: none;
    border-radius: 4px;
    font-size: 1rem;
    cursor: pointer;
}

button:hover {
    background-color: #45a049;
}

p {
    font-size: 1.2rem;
    font-weight: bold;
    color: #333;
    margin-top: 10px;
}

script.js

function calculateAge() {
    const dobInput = document.getElementById('dob').value;
    
    if (!dobInput) {
        document.getElementById('ageResult').textContent = "Please select a valid date of birth.";
        return;
    }
    
    const dob = new Date(dobInput); // Convert input to Date object
    const today = new Date(); // Get the current date
    
    let age = today.getFullYear() - dob.getFullYear();
    const monthDifference = today.getMonth() - dob.getMonth();

    // If birthday hasn't occurred yet this year, subtract 1 from age
    if (monthDifference < 0 || (monthDifference === 0 && today.getDate() < dob.getDate())) {
        age--;
    }
    
    document.getElementById('ageResult').textContent = `Your age is: ${age} years old.`;
}

Javascript code Explanation

Let’s break down the JavaScript code for the Age Calculator function step by step.

Function: calculateAge()

The purpose of this function is to calculate a person’s age based on their Date of Birth (DOB) and display the result on the webpage.

1. Getting the Date of Birth Input

javascriptCopy codeconst dobInput = document.getElementById('dob').value;
  • The dobInput variable retrieves the value of the input field with the ID dob.
  • The input field expects the user to enter their date of birth in a standard date format (e.g., YYYY-MM-DD).
  • The .value property gives the date string that the user selects or enters.

2. Checking if the Date is Valid

javascriptCopy codeif (!dobInput) {
    document.getElementById('ageResult').textContent = "Please select a valid date of birth.";
    return;
}
  • Here, we check if the user has entered a valid date. If the input is empty (i.e., dobInput is falsy), an error message is displayed.
  • The document.getElementById('ageResult').textContent changes the text of the paragraph with the ID ageResult to show a message, prompting the user to select a valid date.
  • The return statement ensures that the function stops executing if no date is selected.

3. Creating Date Objects

javascriptCopy codeconst dob = new Date(dobInput); // Convert input to Date object
const today = new Date(); // Get the current date
  • dob is a JavaScript Date object that represents the user’s Date of Birth (DOB) by passing the dobInput string to the Date constructor. This converts the inputted date string into a valid JavaScript Date object.
  • today is another Date object representing the current date, created by calling new Date(). This provides today’s date as a reference for the age calculation.

4. Calculating the Age in Years

javascriptCopy codelet age = today.getFullYear() - dob.getFullYear();
  • getFullYear() retrieves the year part from both the current date (today) and the date of birth (dob).
  • By subtracting the birth year from the current year, the basic age in years is calculated.
  • At this point, the age might be slightly off, because it doesn’t account for whether the user has already had their birthday this year.

5. Adjusting the Age Based on Month and Day

javascriptCopy codeconst monthDifference = today.getMonth() - dob.getMonth();
  • getMonth() returns the month (from 0 to 11), so this line calculates the difference in months between the current month (today.getMonth()) and the birth month (dob.getMonth()).
  • If the current month is before the birth month, it indicates that the user hasn’t celebrated their birthday yet this year, and the age should be adjusted accordingly.
javascriptCopy code// If birthday hasn't occurred yet this year, subtract 1 from age
if (monthDifference < 0 || (monthDifference === 0 && today.getDate() < dob.getDate())) {
    age--;
}
  • This if condition checks:
    • If the current month is before the birth month (monthDifference < 0), meaning the user’s birthday hasn’t occurred yet this year, or
    • If the current month is the same as the birth month but the current day is before the birthday (today.getDate() < dob.getDate()), meaning the user hasn’t reached their birthday yet in this month.
  • If either condition is true, it subtracts 1 from the age, because the birthday hasn’t happened yet, so the user is technically one year younger than the initial calculation.

6. Displaying the Result

javascriptCopy codedocument.getElementById('ageResult').textContent = `Your age is: ${age} years old.`;
  • Finally, the function updates the text content of the HTML element with the ID ageResult to display the calculated age.
  • The template literal (\Your age is: ${age} years old.`) allows embedding the age` variable within the string. This dynamically shows the result to the user.

Summary of the Flow:

  1. The user inputs their Date of Birth.
  2. The script checks if the input is valid.
  3. It calculates the age in years.
  4. The script adjusts the age if the birthday hasn’t occurred yet this year.
  5. Finally, the calculated age is displayed to the user.

This function is simple but effective in calculating the age accurately, accounting for whether or not the user has already celebrated their birthday in the current year.

Leave a Reply