Overview:
Welcome to our JavaScript Age Calculator from Date of Birth Check Coding Tutorials.
In this article, we'll walk you through a step-by-step guide to building a fully functional advanced-age calculator from scratch using HTML, CSS and of course Javascript. You'll learn how to implement an advanced age calculation from the date of birth effectively. we'll guide you through the process of creating a versatile and feature-rich age calculator that goes beyond just calculating someone's age based on their birthdate.
💫 Watch Live Preview 👉 Age Calculator App
Throughout this video, we'll cover key concepts such as DOM manipulation, event handling, and DATE Operations, enabling you to build an interactive and user-friendly age calculator tool.
📝 Advanced Age Calculator App using JavaScript 👇
By the end of this video, you'll have a feature-rich and interactive age calculator that will show you how much we've already lived In years, months, weeks, days, hours, minutes, and seconds, and we are showing how many days are left for your next Birthday too.
Let's get started on creating your own javascript-advanced age calculator app now! HAPPY CODING!
You might like this: Simple Calculator
If you're already aware of the basics then directly jump to implementation with Step 4.
Introduction:
In a world where every moment counts, the significance of time is undeniable. Time shapes our experiences, marks our milestones, and weaves the tapestry of our lives. Whether you're curious about how many days have passed since a significant event or eager to pinpoint the exact number of years, months, days, weeks, hours, minutes and seconds you've graced this planet, our Age Calculator Tool is here to unravel the mysteries of time.
Our Age Calculator Tool is designed with simplicity and precision to help you effortlessly decode the temporal puzzle of your existence.
Prerequisites:
Basic knowledge of HTML, CSS, and JavaScript.
A code editor of your choice.
Step 1: Set Up Your Project:
Create a new folder for your project, project name as per your wish I have created a project name called Age Calculator and inside it, create three files: index.html
, style.css
, and script.js
. These files will serve as the foundation for your Age calculator. Otherwise, if you want clone my Project-Structure-Example and start working with me.
Step 2: Build the Basic HTML Structure:
In the index.html file, create the HTML structure for your app and add the HTML Boilerplate with linking files (style.css
, script.js
) into an HTML file.
The <link>
tag defines the relationship between the current document and an external resource. (style.css)
The <script>
tag is used to embed a client-side script (JavaScript). or it points to an external script file through the src attribute. (script.js)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Age Calculator - By Sharathchandar.K</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<!-- Container here -->
<script type="text/javascript" src="script.js"></script>
</body>
</html>
First, will add the div
with the class attribute value of the container
inside the body element. The div tag defines a division or a section in an HTML document.
<div class="container">
<!-- Inside the container will add an HTML elements.-->
</div>
Step 3: Style Your App with CSS:
In the style.css
file, and add CSS rules to make your app visually appealing.
We are setting all elements to have zero margins and zero padding, this will make the same in all the browsers. with the help of * and the font family Poppins
and then will set the background color to the entire body with styles to the container too.
@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600&display=swap");
* {
margin: 0;
padding: 0;
font-family: "Poppins", sans-serif;
box-sizing: border-box;
}
body {
background: #78c1f3;
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
.container {
background: #ffffff;
padding: 25px;
width: 450px;
border-radius: 10px;
}
Step 4: Implementing Input Box:
Inside the container will add the element called h2 tag with the value of AGE Calculator, and add another div with a class value of input-box
inside the div will add an input element with the type of date this will help to select a valid date by the user, and will add another image element as an event to hit and calculate the operations with the selected date.
<h2>AGE Calculator</h2>
<div class="input-box">
<input type="date" name="ageValue" id="ageValue" />
<img id="calculateAge" src="images/arrow-right.png" />
</div>
and then will style the above HTML element with the help of the class value.
.container h2 {
text-align: center;
margin-bottom: 15px;
}
.input-box {
display: flex;
justify-content: space-between;
align-items: center;
border-radius: 30px;
margin-bottom: 15px;
background: #78c1f3;
}
.input-box input {
flex: 1;
background: transparent;
border: none;
outline: none;
padding: 15px;
font-size: 18px;
color: #ffffff;
cursor: pointer;
}
.input-box img {
height: 55px;
width: 55px;
background: limegreen;
border-radius: 30px;
padding: 15px;
cursor: pointer;
}
img {
height: 35px;
width: 35px;
}
After adding style to the above input-box
our age calculator looks like the below image with the help of the calendar icon on the text area user can click and able to see the mini calendar this will prevent selecting only dates. so only we have mentioned the input type as date.
Step 4.1: Implementing Output Box to Display Results:
will add the output-box
div element next to the input-box
inside the output box div will display the results based on the selected DOB date from the input box by the user.
Inside the output box will display results like Your Age Is and Your Date of Birth and then below we have displayed a table, inside the table will display multiple information with the selected dates with the header of Your Already Lived and values containing In Years, In Months, In Weeks, In Days, In Hours, In Minutes and In Seconds and end of the list will display Days Left for your Next Birthday.
<div class="output-box">
<label>Your Age is </label>
<div>
<strong id="CurrentAge">0 years 0 Months 0 Days</strong>
<img src="images/age.png" />
</div>
<label>Your Date of Birth is</label>
<div>
<strong id="DOB">Monday, January 00, 0000</strong>
<img src="images/birthday-cake.png" />
</div>
<table>
<thead>
<tr>
<th colspan="2">You Already Lived</th>
</tr>
</thead>
<tbody>
<tr>
<td>In Years</td>
<td><strong id="InYears">0</strong> Years</td>
</tr>
<tr>
<td>In Months</td>
<td><strong id="InMonths">0</strong> Months</td>
</tr>
<tr>
<td>In Weeks</td>
<td><strong id="InWeeks">0</strong> Weeks</td>
</tr>
<tr>
<td>In Days</td>
<td><strong id="InDays">0</strong> Days</td>
</tr>
<tr>
<td>In Hours</td>
<td><strong id="InHours">0</strong> Hours</td>
</tr>
<tr>
<td>In Minutes</td>
<td><strong id="InMinutes">0</strong> Minutes</td>
</tr>
<tr>
<td>In Seconds</td>
<td><strong id="InSeconds">0</strong> Seconds</td>
</tr>
</tbody>
</table>
<div>
<strong id="DaysLeft">0</strong> Days Left for your Next Birthday<img
src="images/confetti.png"
/>
</div>
</div>
and will add the styles to the output box to display the results.
.output-box {
margin: 15px;
}
.output-box div {
display: flex;
align-items: center;
gap: 5px;
padding-left: 10%;
margin-bottom: 5px;
font-weight: 500;
}
.output-box table {
width: 100%;
padding: 15px 0;
}
td {
padding: 5px;
border-bottom: 1px solid #ddd;
}
Step 5: Implement the JavaScript Functionality:
In the script.js
file, which will write the JavaScript code to make your app interactive. Create declarations and functions for manipulating operations in the calculator. You can use the Document Object Model (DOM) to manipulate elements in your HTML.
First will declare all the declarations with the help of a document object, the document object represents the owner of all other objects on your web page.
const ageValue = document.getElementById("ageValue");
const calculateAge = document.getElementById("calculateAge");
const CurrentAge = document.getElementById("CurrentAge");
const DOB = document.getElementById("DOB");
const InYears = document.getElementById("InYears");
const InMonths = document.getElementById("InMonths");
const InWeeks = document.getElementById("InWeeks");
const InDays = document.getElementById("InDays");
const InHours = document.getElementById("InHours");
const InMinutes = document.getElementById("InMinutes");
const InSeconds = document.getElementById("InSeconds");
const DaysLeft = document.getElementById("DaysLeft");
with the help of the above declaration will show all the input/output for the age calculation that the user performed in this app.
now will add another declaration to calculate the DOB operations with the help of these values, new Date() will return the current date and time for others will have basic time declatrions like seconds, minutes, hours and weeks.
const today = new Date();
const seconds = 1000;
const minutes = 60;
const hours = 24;
const week = 7;
and will disable the feature date in the input-box
input type Date for DOB selection because will not be able to calculate the birth calculation from the current date or upcoming dates right?
let maxDate = today.toISOString().substring(0, 10);
ageValue.setAttribute("max", maxDate);
with the help of the date object in javascript will find today's date and will set this date with the help of attribute max to the input box, this will help to disable the feature days like the below image. Users cannot select the feature dates from the input box.
and now will add the code implementation of the Calculate Age event listener with the help of a click once the user selects the DoB from the input box he/she will hit the button next to it. This will calculate all the calculations and place them into the below results.
if the user selects the current date and tries to hit the calculate button tool will show an alert box with the value of "Invalid Date of Birth".
calculateAge.addEventListener("click", function (e) {
if (ageValue.value === maxDate) {
alert("Invalid Date of Birth.");
}
let oneDay = seconds * minutes * minutes * hours;
let oneHour = seconds * minutes * minutes;
let oneMinutes = seconds * minutes;
let birthday = new Date(ageValue.value);
if (ageValue.value !== "") {
let TotalYears =
today.getFullYear() -
birthday.getFullYear() -
(today.getMonth() < birthday.getMonth() ||
(today.getMonth() === birthday.getMonth() &&
today.getDate() < birthday.getDate()));
let TotalMonths =
today.getMonth() -
birthday.getMonth() +
(today.getFullYear() - birthday.getFullYear()) * 12;
let MonthsTotal = Math.abs(birthday.getMonth() - today.getMonth());
let DaysTotal = Math.abs(today.getDate() - birthday.getDate());
let TotalDays = Math.round(
Math.abs(today.getTime() - birthday.getTime()) / oneDay
);
let TotalWeeks = Math.round(
Math.abs(today.getTime() - birthday.getTime()) / (oneDay * week)
);
let TotalHours = Math.round(
Math.abs(today.getTime() - birthday.getTime()) / oneHour
);
let TotalMinutes = Math.round(
Math.abs(today.getTime() - birthday.getTime()) / oneMinutes
);
let TotalSeconds = Math.round(
Math.abs(today.getTime() - birthday.getTime()) / seconds
);
CurrentAge.innerText = `${TotalYears} Years ${MonthsTotal} Months ${DaysTotal} Days`;
DOB.innerText = `${birthday.toLocaleString("default", {
weekday: "long",
})} ${birthday.toLocaleString("default", {
month: "long",
})}, ${birthday.getDate()}, ${birthday.getFullYear()}`;
InYears.innerText = TotalYears;
InMonths.innerText = TotalMonths;
InWeeks.innerText = TotalWeeks;
InDays.innerText = TotalDays;
InHours.innerText = TotalHours;
InMinutes.innerText = TotalMinutes;
InSeconds.innerText = TotalSeconds;
let birthDayThisYear = new Date(
`${today.getFullYear()}-${birthday.getMonth() + 1}-${birthday.getDate()}`
);
if (today > birthDayThisYear) {
birthDayThisYear.setFullYear(today.getFullYear() + 1);
}
let TotalDaysLeft = Math.round(
Math.abs(birthDayThisYear.getTime() - today.getTime()) / oneDay
);
DaysLeft.innerText = TotalDaysLeft;
}
});
once the user selects the DOB on input and hits the calculate event next to it, the tool will display the results like Your Age is with years, months and Days. Ex: 29 Years 0 Months 3 Days.
and next will display the value of the results with Your Date of Birth is with Day, Month Date, and Year. Ex: Thursday, December 1, 1994.
and will display the Detailed list of You Already Lived in with the results of In Years, In Months, In Weeks, In Days, In Hours, In Minutes and In Seconds.
At the end of the list, we have displayed the Days Left for your Next Birthday calculated and displayed results in days.
Step 6: Test and Customize:
Open your index.html
file in a web browser to test your Age Calculator. Now you can perform all the operations to check your Age, Birth Day and Days left for your upcoming birthday, we have added detailed calculations to check how many Months, Weeks, Days, Hours, Minutes and seconds we have lived. You can further customize and enhance your app by implementing features like adding the birth time and getting the exact calculation to be displayed in the detailed view.
Conclusion:
Congratulations! You've successfully created an Age calculator app using HTML, CSS, and JavaScript. This project is an excellent starting point for learning web development and the javascript date object can be expanded with additional features to suit your needs. Happy coding!
Join our ever-growing community on YouTube, where we explore Full Stack development, learn, and have fun together. Your subscription is a vote of confidence, and it enables us to keep producing high-quality, informative videos that you can enjoy and share with your friends and family.
So, if you haven’t already, please hit that subscribe button, click the notification bell, and be a part of our YouTube family. Let’s continue learning, growing, and sharing knowledge in exciting and innovative ways.
Thank you once again for your support, and we look forward to seeing you on our YouTube channel!
Top comments (0)