BMI Calculator using JavaScript with Source code

Explore the world of health and wellness with our BMI Calculator project using JavaScript. In this article, we’ll guide you through the development process and provide you with the source code to create a valuable tool for calculating Body Mass Index, helping users gain insights into their health and fitness.


<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="style.css">
    <title>BMI Calculator</title>
    <div class="container">
    <h1>BMI Calculator</h1>
    <p><label>Height in CM: </label><input type="text" id="height"></p>
    <p><label>Weight in KG: </label><input type="text" id="weight"></p>
    <div id="results"></div>
    <div id="weight-guide">
    <h3>BMI Weight Guide</h3>
    <p>Under Weight = Less than 18.6</p>
    <p>Normal Range = 18.6 and 24.9</p>
    <p>Overweight = Greater than 24.9</p>
<script src="script.js"></script>

.container {
    width: 375px;
    height: 525px;
    margin-left: 350px;
    margin-top: 65px;
    background-color: yellow;
    padding-left: 30px;
#height, #weight {
    width: 150px;
    height: 25px;
    margin-top: 30px;

    margin-left: 75px;
    margin-top: 25px;

    font-size: 35px;
    margin-left: 90px;
    margin-top: 20px;
    color: blue;

    width: 150px;
    height: 35px;
    margin-left: 90px;
    margin-top: 25px;
    border-radius: 5px;
    border-style: none;
    background-color: blue;
    color: #fff;
    font-size: 25px;

    padding-left: 15px;
    padding-top: 25px;

const form = document.querySelector('form');

form.addEventListener('submit', function(e){
    const height = parseInt(document.querySelector('#height').value);
    const weight = parseInt(document.querySelector('#weight').value);
    const results = document.querySelector('#results');
    if((height === '') || (height < 0) || (isNaN(height))){
        //NaN !== NaN
        results.innerHTML = "Please provide a valid height";
    } else if (weight === '' || weight < 0 || isNaN(weight)){
        results.innerHTML = "Please provide a valid weight";
    } else {
    //calculate BMI
    const bmi = (weight / ((height*height)/10000)).toFixed(2);
    //display the results
    results.innerHTML = `<span>${bmi}</span>`

//NaN !== NaN, use the isNaN() function

Leave a Reply