In this project, you will be able to learn how to create a simple age calculator using Javascript, HTML, and CSS. To complete this project you will need to create file according to the below names and copy paste the source code
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="./style.css" type="text/css">
</head>
<body>
<div class="container">
<label for="dob">Your Date of Birth</label>
<input type="date" name="dob-name" id="dob" >
<p class="desc">Your Age is : </p>
<p class="age">
<span id="years"></span> years
<span id="months"></span> months
<span id="days"></span> days
</p>
<p class="error">Welcome Time Traveller 🔮</p>
</div>
<script src="./script.js" type="text/javascript"></script>
</body>
</html>
Style.css
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html,
body {
font-size: 10px;
font-family: 'lato', Arial, Helvetica, sans-serif;
}
body {
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
.container {
display: flex;
flex-direction: column;
text-align: center;
height: 40rem;
min-width: 30rem;
align-items: center;
}
.container label {
font-size: 2rem;
margin-bottom: 1rem;
}
.container #dob {
margin-bottom: 3rem;
}
.container .desc {
font-size: 2rem;
margin-bottom: 4rem;
}
.container .age {
font-size: 3rem;
}
.container .age > span {
font-weight: bold;
}
.error {
display: none;
font-size: 4rem;
}
script.js
const container = document.querySelector('.container');
const error = document.querySelector('.error');
function getAge(){
const dobValue = document.getElementById('dob').value;
//if the dob value is falsy, then simply return
if(!dobValue) return;
//stores dob ----- Date Wed Sep 01 1999 05:30:00 GMT+0530 (India Standard Time)
let dob = new Date(dobValue);
//current date
const today = new Date();
let diff = today - dob;
let age = diff / (1000 * 60 * 60 * 24 * 365); //21.375
calcAge(age);
}
function calcAge(age){
let year = Math.floor(age); //21
let remainingYear = age - year; //0.375
let monthDiff = remainingYear * 12; //4.5
let month = Math.floor(monthDiff); //4
let remainingMonth = monthDiff - month; //0.5
let day = Math.floor(remainingMonth * 30); //15
//display age to UI
displayAge(year, month, day);
}
function displayAge(y,m,d){
const years = document.getElementById('years');
const months = document.getElementById('months');
const days = document.getElementById('days');
years.innerText = y;
months.innerText = m;
days.innerText = d;
if(y >= 0){
error.style.display = `none`;
}
if(y < 0){
error.style.display = `block`;
}
}
container.addEventListener('input', getAge);
Latest posts by Publisher (see all)
- Age calculator using Javascript, HTML & CSS - October 28, 2023
- Navigation bar using HTML & CSS - October 26, 2023
- Calculator using HTML, CSS & JS - October 26, 2023