Age Calculator Javascript Project With Source Code

4 min read Jun 22, 2024
Age Calculator Javascript Project With Source Code

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

  1. Create HTML Structure:

    
    
    
        Age Calculator
    
    
        

    Age Calculator

  2. 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:

  1. 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.
  2. 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

  1. Open the HTML file in a web browser.
  2. Enter your birthdate in the input field.
  3. Click the "Calculate Age" button.
  4. 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!

Latest Posts