How to create a Age Calculator using HTML, CSS and JavaScript

Age Calculator | Coding Zemigle

In this tutorial, we will walk through the process of creating a fully functional age calculator using HTML, CSS, and JavaScript. An age calculator allows users to input their date of birth, and the system calculates their current age. This is a fun and practical project to build your web development skills, especially if you're new to programming with JavaScript.

An age calculator is a simple web application that calculates a person's age based on their date of birth. It’s an excellent project to get hands-on experience with JavaScript's Date object and learn how to manipulate dates effectively. This project can also be extended to learn more advanced concepts like time zones, leap years, or different calendar systems, but we’ll focus on building the core functionality in this tutorial.

Step 01: Setting Up the Project

Start by creating a new folder for this project on your local machine. Inside this folder, create three files:

index.html – for the HTML structure
style.css – for the CSS styles
script.js – for the JavaScript functionality


Once the setup is done, open your text editor and get ready to start coding!

Step 02: Creating the HTML Structure

The HTML file will contain the form input where the user can enter their date of birth, as well as the section to display the calculated age.

Here’s the complete index.html code:

✲    index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Age Calculator | Coding Zemigle</title>
  </head>
  <body>
    <div class="container">
      <div class="input-wrapper">
        <input type="date" id="date-input">
        <button id="calc-age-btn">Get</button>
      </div>
      <div class="output-wrapper">
        <div>
          <span id="years">-</span>
          <p>Years</p>
        </div>
        <div>
          <span id="months">-</span>
          <p>Months</p>
        </div>
        <div>
          <span id="days">-</span>
          <p>Days</p>
        </div>
      </div>
    </div>
  </body>
  <script src="script.js"></script>
</html>



The input tag with type date allows users to select their date of birth from a calendar.

The button triggers the calculateAge function, which we will write in JavaScript.


The <div> element with the ID age will display the calculated age after the user clicks the button.

Step 03: Styling the Calculator with CSS

Now, let’s style the age calculator so it looks visually appealing. Open the style.css file and add the following code:

✲    style.css
* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  font-family: "Roboto", sans-serif;
}

body {
  background-color: #1F7A8C;
  margin: 0;
}

.container {
  width: 90%;
  position: absolute;
  transform: translate(-50%, -50%);
  top: 50%;
  left: 50%;
}

.input-wrapper {
  background-color: #ffffff;
  padding: 0.8rem 1rem;
  border-radius: 0.5rem;
  margin-bottom: 2rem;
  display: grid;
  grid-template-columns: 9fr 3fr;
  gap: 1rem;
}

input {
  background-color: #f5f5f5;
  color: #080808;
  border: none;
  padding: 1rem;
  font-size: 1rem;
}

button {
  color: #ffffff;
  background-color: #1F7A8C;
  border-radius: 0.3rem;
  border: none;
  font-size: 20px;
  font-weight: 500;
}

.output-wrapper {
  width: 100%;
  display: flex;
  justify-content: space-between;
}

.output-wrapper div {
  height: 6.25rem;
  width: 6.8rem;
  background-color: #ffffff;
  border-radius: 0.3rem;
  color: #080808;
  display: grid;
  place-items: center;
  padding: 1.25em 0;
}

span {
  font-size: 1.87rem;
  font-weight: 500;
}

p {
  font-size: 0.87rem;
  color: #707070;
  font-weight: 400;
}



The body is centered using Flexbox to ensure the calculator is positioned in the middle of the screen.

The age container is styled with padding, background color, shadow, and rounded corners.

The form inputs and buttons are styled for better user experience, and the result is displayed with a larger font size for visibility.


Step 04: Adding Functionality with JavaScript

Now, let’s implement the JavaScript to calculate the age based on the user’s input.

Open the script.js file and add the following code:

✲    script.js
const ageCalculate = () => {
  const today = new Date();
  const inputDate = new Date(document.getElementById("date-input").value);

  const birthDetails = {
    date: inputDate.getDate(),
    month: inputDate.getMonth() + 1,
    year: inputDate.getFullYear(),
  };

  const currentYear = today.getFullYear();
  const currentMonth = today.getMonth() + 1;
  const currentDate = today.getDate();

  if (isFutureDate(birthDetails, currentYear, currentMonth, currentDate)) {
    alert("Not Born Yet");
    displayResult("-", "-", "-");
    return;
  }

  const { years, months, days } = calculateAge(
    birthDetails,
    currentYear,
    currentMonth,
    currentDate
  );

  displayResult(days, months, years);
};

const isFutureDate = (birthDetails, currentYear, currentMonth, currentDate) => {
  return (
    birthDetails.year > currentYear ||
    (birthDetails.year === currentYear &&
      (birthDetails.month > currentMonth ||
        (birthDetails.month === currentMonth &&
          birthDetails.date > currentDate)))
  );
};

const calculateAge = (birthDetails, currentYear, currentMonth, currentDate) => {
  let years = currentYear - birthDetails.year;
  let months, days;

  if (currentMonth < birthDetails.month) {
    years--;
    months = 12 - (birthDetails.month - currentMonth);
  } else {
    months = currentMonth - birthDetails.month;
  }

  if (currentDate < birthDetails.date) {
    months--;
    const lastMonth = currentMonth === 1 ? 12 : currentMonth - 1;
    const daysInLastMonth = getDaysInMonth(lastMonth, currentYear);
    days = daysInLastMonth - (birthDetails.date - currentDate);
  } else {
    days = currentDate - birthDetails.date;
  }
  return { years, months, days };
};

const getDaysInMonth = (month, year) => {
  const isLeapYear = year % 4 === 0 && (year % 100 != 0 || year % 400 === 0);
  const getDaysInMonth = [
    31,
    isLeapYear ? 29 : 28,
    31,
    30,
    31,
    30,
    31,
    31,
    30,
    31,
    30,
    31,
  ];
  return getDaysInMonth[month - 1];
};

const displayResult = (bdate, bMonth, bYear) => {
  document.getElementById("years").textContent = bYear;
  document.getElementById("months").textContent = bMonth;
  document.getElementById("days").textContent = bdate;
};

document.getElementById("calc-age-btn").addEventListener("click", ageCalculate);



We first check if the user has entered a valid date of birth. If not, we show an alert.

We use JavaScript's Date object to get the current date and the date of birth. Then, we calculate the difference in years. We also handle edge cases where the user’s birthday hasn’t occurred yet in the current year by adjusting the age accordingly.

Finally, the result is displayed inside the age span element.

Conclusion

Congratulations! You’ve successfully built an age calculator using HTML, CSS, and JavaScript. This project not only helps you practice working with JavaScript’s Date object but also enhances your ability to manipulate user input, display results, and improve your front-end design skills.

This simple age calculator can be extended in many ways. You can add features like calculating the exact number of months or days, validating the user’s input with custom messages, or making the interface more interactive with additional animations or styles.

Feel free to experiment and make this project your own. Happy coding!