In this blog;
I will walk you through a step-by-step process to create a simple BMI Calculator.
I assume you can create HTML and CSS File for this, so I am not making it for you. Although, I will provide my version of the HTML and CSS code below for your convenience.
In this blog, I focus mainly on the JavaScript part of this BMI Calculator.
<!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>BMI CALCULATOR</title>
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<div>
<h1 style="text-align: center">BMI CALCULATOR</h1>
<h3>What is BMI?</h3>
<p class="para">
BMI stands for Body Mass Index, which is a measure of body fat based on a person's weight and height. It is commonly used to assess whether a person is underweight, normal weight, overweight, or obese. BMI is calculated by dividing a person's weight (in kilograms) by their height(in meters squared).
</p>
<p class="para">
BMI is a useful tool to assess whether a person is at a healthy weightor not, but it is not always a perfect indicator of health. For example,someone with a high amount of muscle mass may have a high BMI even though they are not overweight or obese. Additionally, BMI does not take into account other factors such as age, sex, or body composition, so it should be used in conjunction with other measures to assess overall
health.
</p>
<h3>Ranges</h3>
<p class="para">
BMI ranges are typically categorized into different levels of bodyweight and are used to indicate whether a person is underweight, normalweight, overweight, or obese. The World Health Organization (WHO) has established the following BMI ranges for adults:
</p>
<ul class="para">
<li>Underweight: BMI below 18.5</li>
<li>Normal weight: BMI between 18.5 and 24.9</li>
<li>Overweight: BMI between 25 and 29.9</li>
<li>Obese: BMI 30 or higher</li>
</ul>
<section class="work">
<h2 class="top">Calculate your BMI</h2>
<p class="weight"><b>Enter Your Weight in kg</b></p>
<input type="number" id="weightInput" />
<p class="height"><b>Enter your height in meters</b></p>
<input type="number" id="heightInput" />
<br />
<button
type="submit
"
id="btn"
>
Calculate
</button>
</section>
<h1 id="result">Your BMI is</h1>
<footer>
<p class="foot" style="text-align: center">
Made with ❤ by SHASHANK SHARMA ©2023
</p>
</footer>
</div>
<script src="script.js"></script>
</body>
</html>
body {
margin: 0;
padding-left: 350px;
padding-right: 350px;
overflow: auto;
box-sizing: border-box;
background-color: #ecf2ff;
}
div {
border: 5px solid black;
padding: 40px;
}
.top {
font-size: 40px;
color: white;
}
.para {
font-size: 18px;
}
.work {
text-align: center;
background-color: #3e54ac;
}
#result {
text-align: center;
}
.weight {
font-size: 24px;
}
.height {
font-size: 24px;
}
.foot {
color: black;
border: 2px solid black;
padding: 20px;
font-size: 20px;
}
#btn {
margin-top: 15px;
padding: 9px 40px;
background-color: black;
color: white;
}
/* CSS MEDIA QUERIES */
@media only screen and (max-width: 600px) {
/* Adjust font sizes */
h1 {
font-size: 2rem;
}
h2 {
font-size: 1.5rem;
}
h3 {
font-size: 1.2rem;
}
p {
font-size: 1rem;
}
/* Center align text */
h1,
h2,
h3,
p {
text-align: center;
}
/* Adjust padding and margins */
body {
padding: 0.5rem;
}
.para {
margin: 0.5rem;
}
/* Adjust input field sizes */
#weightInput,
#heightInput {
width: 100%;
margin-bottom: 0.5rem;
}
}
@media only screen and (min-width: 600px) and (max-width: 1200px) {
/* Adjust font sizes */
h1 {
font-size: 3rem;
}
h2 {
font-size: 2rem;
}
h3 {
font-size: 1.5rem;
}
p {
font-size: 1.2rem;
}
/* Adjust padding and margins */
body {
padding: 1rem;
}
.para {
margin: 1rem;
}
/* Adjust input field sizes */
#weightInput,
#heightInput {
width: 50%;
margin-bottom: 1rem;
}
}
To help you understand more easily, I divided the codes into 7 steps, So that you can understand the logic clearly without creating any mess.
var :- Creating a variable
valueOne :- The name we have given to our variable
document:- The document from which we are selecting the element
getElementById(“ ”) :- Id selector to select the element with a unique ID
(“weightInput”) :- The name of the Id.
By joining all the above parts, our code will look something like this;
var valueOne = document.getElementById("weightInput");
Lets deep dive into this and try to understand it clearly:-
First thing first, I create a variable to store the value which the user enters in the input field.
Next, I give the variable the name “valueOne”, you can give it any name you want.
Now, after creating the variable and giving it a name, I can now move to the interesting part, accessing the value entered by the user in the input field.
As known already, I can select any element, change its value, get the value from it, and do many more things using DOM(Document Object Model).
first I select the document from which I will be accessing the information, in this case, an HTML document.
After that, I select the desired element from the document using the selector.
Next, I give the unique Id to the element I am selecting, so I am using the ID selector:- getElementById(“ ”).
After all these steps, I will get the value entered by the user in the “weightInput” field.
var valueTwo = document.getElementById("heightInput");
Now, after getting both the values and storing those values in our variables, it's time to handle the calculations.
I can do the calculation here with two methods:-
Method-1:- by simply retrieving the values, storing them in variables, and doing the calculation.
Method-2:- by using the function()
Let's see both methods and figure out which one works well for us.
var weight = document.getElementById("weightInput").value;
var height = document.getElementById("heightInput").value;
var bmi = Math.round(weight / (height * height));
Math.round
written there and you might be thinking what is it for?function bmiCalc(weight, height) {
var bmi = Math.round(weight / (height * height));
return bmi;
}
Here,
I first created a function and give it the name of bmiCalc
As Known already, the function takes two arguments. In this case, those two arguments are ‘weight’ and ‘height’
Then I did the same as what I did early, imbedded the formula in a new variable with Math.round
return bmi => returns the output after the calculation is done.
Que) WHICH METHOD SHOULD WE USE HERE?
Ans) The Function Method()
The function method is more appropriate here as it can be reused again. Also by using the function, I can separate the ‘calculation logic’ and the ‘code that retrieves the input values’.
Calculation logic:- a function that takes two arguments, in this case, ‘weight’ and ‘height’, and then calculate BMI using a formula.
Code that retrieves input value:- Here, I am talking about getElementById(“ ”), Which is retrieving information from the document.
Now, it's time to make the BMI calculator more functional and write some more code for the ‘button’ element, so that when the user enters height and weight and clicks the button, BMI gets displayed on the screen.
I created a button in our HTML file and gave it an Id of ‘btn’.
Let’s access this button and start playing with it.
Now, by this time I think you guys should know how we can access the element from the document.
var valueThree = document.getElementById("btn");
(SKIP THIS STEP IF YOU ALREADY KNOW ABOUT EVENT LISTENERS)
Que) WHAT IS EVENT LISTENER?
Ans) Event listener is a function that we attach to an HTML element and then it listens for the specific event to happen, be it a mouse click, or keyboard input, or anything else.
It takes two arguments;
first is the ‘event’ that is happening, in this case, click event
function block, to execute a specific block of code that we want to work when the click happens.
var button = document.querySelector('button');
button.addEventListener('click', function() {
alert('I got clicked!');
});
In the above dummy code, we accessed the button using a query selector and then added an event listener to it.
After that, we write the code that whenever a user clicks on the button, an alert of ‘I got clicked!’ pops onto the screen.
valueThree.addEventListener("click", function () {
var weight = document.getElementById("weightInput").value;
var height = document.getElementById("heightInput").value;
var bmi = bmiCalc(weight, height);
By reading Step-5, I now know that an event listener takes two arguments.
First, I provide a click argument because here the ‘click’ is the event that is happening
Second, I assigned a function that stores input values in variables, does the calculation, and returns the BMI value.
Now, when a user enters weight and height and presses the button, the event listener listens to the click, calls the function and the code gets executed.
Now as the user gets the BMI Values, I want to give specific messages to the user according to the BMI value they received.
For that, I used conditionals.
I covered the conditionals in my previous blog so check that out before reading the code below.
document.getElementById("result").innerHTML = "Your BMI is = " + bmi;
if (bmi < 18.5) {
document.getElementById("result").innerHTML =
"Your BMI is " + bmi + ", You are Underweight.";
} else if (bmi >= 18.5 && bmi <= 24.9) {
document.getElementById("result").innerHTML =
"Your BMI is " + bmi + ", You are in Normal weight. Keep Maintaining this.";
} else if (bmi >= 25 && bmi <= 29.9) {
document.getElementById("result").innerHTML =
"Your BMI is " +
bmi +
", You are Overweight. Try to do workout 2-3 days in week.";
} else if (bmi > 30) {
document.getElementById("result").innerHTML =
"Your BMI is " +
bmi +
", You are Obese. Try to do workout 5-6 days in week.";
}
});
That's it for this blog!
I tried to explain this in the easiest way possible, so if you like the blog and if you think you learn something new today, make sure to leave a like and comment.
Make sure to leave your important feedback, so that I can improve my future blogs.
Also published here.