Age Calculator JavaScript Project with Source Code
This project will guide you through creating a simple yet functional age calculator using JavaScript. This project is suitable for beginners and serves as a good introduction to basic JavaScript concepts.
Project Setup
-
Create HTML Structure:
Age Calculator Age Calculator
-
Create JavaScript File: Create a new file named
script.js
in the same directory as your HTML file.
JavaScript Code: script.js
function calculateAge() {
// Get the birthdate from the input field
const birthdate = document.getElementById("birthdate").value;
// Validate the input
if (birthdate === "") {
alert("Please enter your birthdate.");
return;
}
// Calculate the age
const today = new Date();
const birthDate = new Date(birthdate);
let age = today.getFullYear() - birthDate.getFullYear();
const monthDiff = today.getMonth() - birthDate.getMonth();
// Adjust age if the birthday has not yet passed this year
if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
// Display the result
document.getElementById("result").textContent = "You are " + age + " years old.";
}
Explanation:
-
HTML Structure:
- The HTML code defines a simple form with an input field for the birthdate, a button to trigger the calculation, and a paragraph element (
<p>
) where the result will be displayed.
- The HTML code defines a simple form with an input field for the birthdate, a button to trigger the calculation, and a paragraph element (
-
JavaScript Code:
calculateAge()
function: This function is called when the "Calculate Age" button is clicked.- Input Validation: The code first checks if the user has entered a birthdate. If not, an alert message is displayed.
- Date Calculation:
today
: Creates a new Date object representing the current date.birthDate
: Creates a new Date object from the input birthdate.- The code then subtracts the birth year from the current year to get the age.
- Age Adjustment: The code further checks if the birthday has already passed this year. If not, it subtracts 1 from the calculated age.
- Display Result: Finally, the calculated age is displayed in the
result
paragraph element.
Running the Code
- Open the HTML file in a web browser.
- Enter your birthdate in the input field.
- Click the "Calculate Age" button.
- The calculated age will be displayed in the paragraph element below the button.
This is a basic age calculator. You can further enhance it by adding features like:
- Displaying age in months and days.
- Providing feedback based on the user's age.
- Styling the HTML elements for better user experience.
This project provides a solid foundation for exploring JavaScript and web development. Feel free to experiment with the code and add your own creative touches!