Create an age calculator using html, Css & JavaScript
Welcome to our latest blog post, where we'll guide you through the process of creating an age calculator using HTML, CSS, and JavaScript. This handy tool will allow users to input their date of birth and instantly calculate their age in years, months, and days. Whether you're a beginner or an experienced developer, this tutorial will provide you with valuable insights into front-end development and help you sharpen your coding skills.
In this step-by-step guide, we'll cover everything from setting up the HTML structure and styling it with CSS to implementing the age calculation logic using JavaScript. By the end of this tutorial, you'll have a fully functional age calculator that you can integrate into your website or use as a standalone project. So, let's dive in and start building your very own age calculator!
Project Live Preview
We will use HTML to create basic structure of our web page.
Html Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Age Calculator </title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<form>
<div class="base">
<div class="enter">
<h4>Age Calculator</h4>
</div>
<div class="block">
<p class="title">Date</p>
<input type="number" pattern="^[0-9]" name="date" id="date" placeholder="dd" required="required" minlength="1"
maxlength="2" />
</div>
<div class="block">
<p class="title">Month</p>
<input type="number" pattern="^[0-9]" name="month" id="month" placeholder="mm" required="required" minlength="1"
maxlength="2" />
</div>
<div class="block">
<p class="title">Year</p>
<input type="number" pattern="^[0-9]" name="year" id="year" placeholder="yyyy" required="required" minlength="4"
maxlength="4" />
</div>
</div>
<div class="base">
<div class="enter">
<input type="button" name="submit" value="Submit" onclick="age()" />
</div>
</div>
<div id="age"></div>
</form>
</div>
<script src="app.js"></script>
</body>
</html>
<!DOCTYPE html>: This is the document type declaration, which tells the browser that this is an HTML5 document.
<html lang="en">: This is the opening tag of the HTML document, and it specifies the language of the document.
<head>: This is the head section of the HTML document, which contains information about the document that is not displayed on the page. This section contains metadata, such as the character encoding, the viewport settings, and the page title.
<meta charset="UTF-8">: This specifies the character encoding used in the document.
<meta http-equiv="X-UA-Compatible" content="IE=edge">: This tag is used to instruct Internet Explorer to use the latest version of its rendering engine to display the page.
<meta name="viewport" content="width=device-width, initial-scale=1.0">: This sets the viewport size to the device width and sets the initial zoom level to 1.0.
<title>Age Calculator </title>: This sets the title of the page that will be displayed in the browser tab.
<link rel="stylesheet" href="style.css">: This links an external CSS file called "style.css" to the HTML document.
<body>: This is the body section of the HTML document, which contains the content that will be displayed on the page.
<div class="container">: This is a container element that groups related elements together.
<form>: This is a form element that contains the input fields and submit button.
<div class="base">: This is a container element that groups related elements together within the form.
<div class="enter">: This is a container element that groups the heading and submit button together.
<h4>Age Calculator</h4>: This is a heading element that displays the text "Age Calculator" on the page.
<div class="block">: This is a container element that groups the label and input field together.
<p class="title">Date</p>: This is a paragraph element that displays the label "Date" on the page.
<input type="number" pattern="^[0-9]" name="date" id="date" placeholder="dd" required="required" minlength="1" maxlength="2" />: This is an input field that allows the user to enter their birth date. It has several attributes, such as the input type, pattern, name, id, placeholder, required, minlength, and maxlength.
<div id="age"></div>: This is an empty div element that will be used to display the calculated age.
<script src="app.js"></script>: This links an external JavaScript file called "app.js" to the HTML document. The JavaScript file contains the function that calculates the age based on the input values.
Then we will use CSS to style our application.
CSS Code:
body {
font-family: Arial, Helvetica, sans-serif;
background-color: rgb(249 115 22);
font-size: 15px;
line-height: 1.5;
padding: 0;
margin: 0;
}
* {
box-sizing: border-box;
}
.container {
width: 520px;
height: auto;
margin: 100px auto;
background-color: #eee;
border-radius: 0.25rem;
}
.base {
width: 100%;
margin: 0;
overflow: hidden;
display: block;
float: none;
}
.block {
width: 135px;
padding: 5px 20px;
margin-left: 20px;
display: inline-block;
float: left;
}
.base h4 {
font-size: 26px;
text-align: center;
font-family: sans-serif;
font-weight: normal;
margin-top: 0px;
box-shadow: 0px 2px #bababa;
background: white;
font-size: 34px;
color: rgb(251 146 60);
border-top-right-radius: .25rem;
border-top-left-radius: .25rem;
}
.title {
font-size: 20px;
text-align: left;
font-family: sans-serif;
font-weight: normal;
line-height: 0.5;
letter-spacing: 0.5px;
word-spacing: 2.7px;
color: rgb(251 146 60);
}
input[type="number"] {
width: 140px;
margin: auto;
outline: none;
min-height: 50px;
border: 2px solid rgb(253 186 116);
padding: 12px;
background-color: #f7f7f7;
border-radius: 2px;
color: rgb(253 186 116);
font-size: 17px;
}
input[type="number"]:focus {
border: 2px solid rgb(249 115 22);
outline: none;
}
input[type="button"] {
width: 150px;
margin-left: 35%;
margin-top: 40px;
outline: none;
border: none;
border-radius: 2px;
background-color: rgb(194 65 12);
color: #ffffff;
padding: 14px 16px;
text-align: center;
font-size: 16px;
transition-duration: 150ms;
cursor: pointer;
}
input[type="button"]:hover {
background-color: rgb(249 115 22);
}
#age {
display: block;
margin: 10px;
margin-top: 35px;
padding: 10px;
padding-bottom: 20px;
overflow: hidden;
font-family: verdana;
font-size: 23px;
font-weight: normal;
line-height: 1.5;
word-spacing: 2.7px;
color: rgb(249 115 22);
}
@media (max-width: 640px) {
.block{
width: 100%;
margin-left: 0;
}
.block,.title{
text-align: center;
}
.container{
width: auto;
margin: 0.5rem;
}
input[type="number"]{
width: 100%;
}
.enter{
text-align: center;
}
input[type="button"]{
width: 95%;
margin-left: 0;
}
}
- The first selector sets some basic styling for the entire page, including the font family, background color, font size, line height, padding, and margin.
- The universal selector * applies box-sizing border-box to all elements on the page, ensuring that padding and borders are included in the width and height calculations.
- The .container selector sets the width, height, margin, background color, and border radius for a specific container on the page.
- The .base selector sets the width, margin, overflow, display, and float for a base element, and the .block selector sets the width, padding, margin, display, and float for a block element.
- The .base h4 selector styles a specific heading element, including the font size, text alignment, font family, font weight, margin, box shadow, background color, font color, and border radius.
- The .title selector styles a specific title element, including the font size, text alignment, font family, font weight, line height, letter spacing, word spacing, and font color.
- The input[type="number"] selector styles a specific input element of type number, including the width, margin, outline, minimum height, border, padding, background color, border radius, font size, and font color. The :focus pseudo-class modifies the styling of the input element when it is in focus.
- input[type="button"]: This selector applies styles to all input elements with a type attribute of "button". It sets the width, margin, outline, border, border-radius, background-color, color, padding, text-align, font-size, transition-duration, and cursor properties. The background-color is set to rgb(194 65 12), and changes to rgb(249 115 22) when hovered over with the mouse cursor.
- input[type="button"]:hover: This selector applies styles to all input elements with a type attribute of "button" when they are being hovered over with the mouse cursor. It changes the background-color to rgb(249 115 22).
- #age: This selector targets the element with the id attribute of "age". It sets various styles including the display, margin, padding, overflow, font-family, font-size, font-weight, line-height, word-spacing, and color. It sets the font color to rgb(249 115 22).
- @media (max-width: 640px): This media query applies the styles within its block when the screen width is equal to or less than 640px. It changes the styles of various elements, such as setting the width of .block to 100%, and changing the text-align property of .block and .title to center. It also sets the width of .container to auto, and changes the width property of input[type="number"] to 100%. Additionally, it changes the width property of input[type="button"] to 95% and removes the margin-left property. Lastly, it aligns the text within .enter to the center.
JavaScript Code:
function age() {
var d1 = document.getElementById("date").value;
var m1 = document.getElementById("month").value;
var y1 = document.getElementById("year").value;
if(!d1 || d1 > 31 || d1 < 0 || !m1 || m1 > 12 || m1 < 0 || !y1){
alert("Please Enter Valid Date");
document.getElementById("age").innerHTML = ""
return;
}
var date = new Date();
var d2 = date.getDate();
var m2 = 1 + date.getMonth();
var y2 = date.getFullYear();
var month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
if (d1 > d2) {
d2 = d2 + month[m2 - 1];
m2 = m2 - 1;
}
if (m1 > m2) {
m2 = m2 + 12;
y2 = y2 - 1;
}
var d = d2 - d1;
var m = m2 - m1;
var y = y2 - y1;
if(y < 0){
alert("Please Enter Valid Date");
document.getElementById("age").innerHTML = ""
return;
}
if(y > 122){
document.getElementById("age").innerHTML =
"Your Age is " + y + " Years " + m + " Months " + d + " Days. Rest in your grave";
} else{
document.getElementById("age").innerHTML =
"Your Age is " + y + " Years " + m + " Months " + d + " Days";
}
}
This code defines a function called age()
that calculates a person's age based on the input values of their birth date.
The function starts by declaring three variables d1
, m1
, and y1
and assigning them the values of the day, month, and year of the user's birth date, respectively. These values are obtained from the input fields in the HTML document with the ids "date", "month", and "year" using the getElementById()
method.
The function then checks if the input values are valid or not. If the day is greater than 31, less than 0, or empty, or the month is greater than 12, less than 0, or empty, or the year is empty, the function displays an alert message asking the user to enter valid date and clears the output HTML element with the id "age" by setting its innerHTML
property to an empty string, and returns from the function.
Next, the function declares a variable date
and assigns it the current date obtained using the Date()
constructor. It then extracts the day, month, and year values of the current date into the variables d2
, m2
, and y2
, respectively.
The function then creates an array called month
with the number of days in each month, starting with January. It checks if the input day value d1
is greater than the current day value d2
. If so, it adds the number of days in the current month m2 - 1
to d2
and subtracts 1 from m2
.
The function then checks if the input month value m1
is greater than the current month value m2
. If so, it adds 12 to m2
and subtracts 1 from y2
.
The function then calculates the person's age in years, months, and days, by subtracting the input year value y1
from the current year value y2
, and similarly subtracting the input month value m1
from the current month value m2
, and the input day value d1
from the current day value d2
.
The function then checks if the calculated age y
is less than 0, which means the user has entered a future date, and displays an alert message asking the user to enter valid date and clears the output HTML element with the id "age" by setting its innerHTML
property to an empty string, and returns from the function.
Finally, the function checks if the calculated age y
is greater than 122, which is the maximum human lifespan according to Guinness World Records. If so, it sets the innerHTML
property of the output HTML element with the id "age" to a message that includes the person's age in years, months, and days, and a humorous remark "Rest in your grave". Otherwise, it sets the innerHTML
property of the output HTML element with the id "age" to a message that includes the person's age in years, months, and days.
Download the Source Code