Let’s start by creating the structure of our age calculator using HTML. Open your text editor and create a new HTML file.
<!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>
<div class="form">
<label for="dob">Date of Birth:</label>
<input type="date" id="dob">
<button onclick="calculateAge()">Calculate Age</button>
</div>
<div class="result">
<p>Your age is:</p>
<p id="ageResult">0 years, 0 months, 0 days</p>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
Styling with CSS
To make our age calculator visually appealing, let’s add some CSS to a separate styles.css file. Here’s a simple CSS stylesheet to get you started:
body {
font-family: Arial, sans-serif;
background-color: #f5f5f5;
margin: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.container {
background-color: #fff;
padding: 20px;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
text-align: center;
}
h1 {
color: #333;
}
.form {
margin: 20px 0;
}
label {
font-weight: bold;
}
input[type="date"] {
padding: 5px;
border: 1px solid #ccc;
border-radius: 5px;
font-size: 16px;
}
button {
background-color: #007BFF;
color: #fff;
border: none;
padding: 10px 20px;
border-radius: 5px;
font-size: 16px;
cursor: pointer;
}
.result {
margin-top: 20px;
font-size: 18px;
}
Calculating Age with JavaScript
Now, let’s add the functionality to calculate the age using JavaScript. Create a script.js file and add the following code:
function calculateAge() {
const dobInput = document.getElementById('dob').value;
const dob = new Date(dobInput);
const currentDate = new Date();
const ageInMilliseconds = currentDate - dob;
const ageInYears = ageInMilliseconds / (365 * 24 * 60 * 60 * 1000);
const age = Math.floor(ageInYears);
currentDate.setFullYear(currentDate.getFullYear() - age);
const monthDiff = currentDate.getMonth() - dob.getMonth();
let months = monthDiff;
if (currentDate.getDate() < dob.getDate()) {
months--;
}
let days = currentDate.getDate() - dob.getDate();
if (days < 0) {
const lastDayOfMonth = new Date(currentDate.getFullYear(), currentDate.getMonth(), 0).getDate();
days = lastDayOfMonth - dob.getDate() + currentDate.getDate();
}
document.getElementById('ageResult').textContent = `${age} years, ${months} months, ${days} days`;
}
Learn more in detail with complete source code with code explanation here: Age Calculator Using HTML, CSS, and JavaScript: A Beginner’s Guide
Top comments (0)