Skip to content

Build an Age Calculator Using HTML5 & CSS3 (Javascript Project)

Months, Days, Weeks, Hours, Minutes & Seconds in Browser

index.html

<!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>Javascript Age Calculator </title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<body>
    <div class="container">
        <h1 class="text-center">
            Javascript Age Calculator
        </h1>

        <form id="form">
            <div class="form-group container">
                <label for="age">Write Your Age in Years:</label>
                <input class="form-control" type="text" id="age" required placeholder="Write Your Age in Years:">
            </div>

    <!-- Age input field. -->


    <!-- Calculate Button. -->
            <div class="form-group container">
                <button class="btn btn-danger btn-block">
        <!-- Age Input Field Value. -->
                    Calculate Age

        <!-- Funtion Call-->
                </button>
            </div>
        </form>

        <div id="result">

        </div>

    </div>
</body>
<script>
    let form = document.querySelector('#form')

    // Form Submit Event

    form.addEventListener('submit',(e) => {

        // Prevent Default
        e.preventDefault()

        // Function Call
        let age = document.querySelector('#age').value



    // Function to calculate age.
        calculateAge(age)
    })

    function calculateAge(age){

        // Days // Months // Weeks // Hours // Minutes // Seconds

        let days = age * 365

        let months = days / 30

        let weeks = days / 7

        let hours = days * 24 

        let minutes = days * 24 * 60

        let seconds = days * 24 * 60 * 60

        let result = document.querySelector('#result')
        // Creating a Dynamic Table

        let table = `
        
        <table class="table table-striped">
            
            <thead>
                <tr>
                    <th>Days</th>
                    <th>Months</th>
                    <th>Weeks</th>
                    <th>Hours</th>
                    <th>Minutes</th>
                    <th>Seconds</th>
                </tr>    
            </thead>

            <tbody>
                <tr>
                    <td>${days}</td>
                    <td>${months}</td>
                    <td>${weeks}</td>
                    <td>${hours}</td>
                    <td>${minutes}</td>
                    <td>${seconds}</td>
                </tr>
            </tbody> 
        </table
        
        `
        // Inserting Dynamic Table in the Result Div

    
        result.innerHTML = table

    }
</script>
</html>