top of page
Writer's pictureWeb Coding

How to create a BMI calculator with JavaScript

Today I will be teaching you how to create a BMI Calculator using only HTML, CSS and JavaScript.



HTML

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>Document</title>
</head>
<body>
 <!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>Document</title>
 <link rel="stylesheet" href="style.css">
</head>
<body>
 <div id="BMICalc">
 <h2>BMI Calculator</h2>
 <div class="row"> <p class="column">Height (cm): </p> <input type="number" class="column1" id="height"></div>
 <div class="row"> <p class="column">Weight (kg):</p> <input type="number" class="column1" id="weight"></div>
 <div class="row"> <button id="calculate">Calculate BMI</button> </div>
 <div class="row"><p id="BMI" class="column">BMI:</p> <span id="result" class="column1"></span> </div>
 </div>
 <script src="script.js"></script>
</body>

</html>
</body>
</html>

CSS

*{
 padding0;
 margin0;
}

body{
 min-height100vh;
 displayflex;
 align-itemscenter;
 justify-contentcenter;
 background-color#19181A;
}

#BMICalc{
 background-color#A16E83;
 border1px solid black;
 min-height20vh;
 width50%;
 border-radius25px;
 font-size16px;
}

h2{
 padding-top3vh;
 text-aligncenter;
 padding-bottom1vh;
}

#calc p{
 text-alignend;
}

.row {
 displayflex;
 flex-directionrow;
 justify-contentcenter;
  }
 

.column {
 flex-basis25%;
 margin-right1%;
}

.column1 {
 flex-basis45%;
 margin-left1%;
}

#Calculate{
 margin-top5px;
}

JavaScript

let height = document.getElementById('height');
let weight = document.getElementById('weight');
let calcBtn = document.getElementById('calculate');
let resultDisplay = document.getElementById('result');

calcBtn.addEventListener('click'calculateBMI);

function calculateBMI(){
 let BMI = ((weight.value / height.value / height.value)
    * 10000).toFixed(2);
 if (BMI < 18.5){
 resultDisplay.innerHTML = BMI + " you are considered underweight";
    } else if (BMI >= 18.5 && BMI < 25 ){
 resultDisplay.innerHTML = BMI + " you are considered normal weight";
    } else if (BMI >= 25 && BMI<30){
 resultDisplay.innerHTML = BMI + " you are considered overweight";
    } else {
 resultDisplay.innerHTML = BMI + " you are considered obese";
    }
}

If you found this blog post helpful don’t forget to check out my other projects and if you want more content follow me on


YouTube: https://www.youtube.com/channel/UC2nxqB2usQIS2c8zwVZKWEQ

Instagram: https://www.instagram.com/coding_for_the_web/

Twitter: https://twitter.com/LearnWebCoding

12 views

Comments


bottom of page