HOW TO MAKE BMI CALCULATOR
Tags: javascript, webdev, frontend, programming
Published: 2023-03-18 12:03:51

- 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 &copy;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;
  }
}
```
Now, Let's move to the interesting part, which is JavaScript.

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.

## STEP-1

1) var :- Creating a variable

2) valueOne :- The name we have given to our variable

3) document:- The document from which we are selecting the element

4) getElementById(“ ”) :- Id selector to select the element with a unique ID

5) (“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 have to create a variable to store the value which the user enters in the input field.

- Here, I am giving the variable the name “valueOne”, you can give any name you want.

- Now after creating the variable and giving it a name, I can now move to the interesting part, now I have to access 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.

- If you wanna learn about selectors, check out this blog of mine:- "[Understanding DOM(Document Object Model)](https://shashnode.hashnode.dev/understanding-domdocument-object-model)"

- Here, I give the unique Id to the element I am selecting, so I am using the ID selector:- getElementById(“ ”).

- Now, after doing all these steps, I will get the value entered by the user in the “weightInput” field.

## STEP-2

```
var valueTwo = document.getElementById("heightInput");
```

- Everything I did in step-1, goes exactly the same for step-2, except the variable name and Id name.

- I gave the variable a new name here to store the “heightInput” value entered by the user.

- I also changed the Id name to #heightInput

- I want to store the height and weight values separately, That’s Why I change these two things.

## STEP-3

- Now, after getting both the values and storing those values in our variables, it's time to do the calculation.

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.

**Method-1:- by simply retrieving the values, storing them in variables, and doing the calculation.**

```
var weight = document.getElementById("weightInput").value;
var height = document.getElementById("heightInput").value;
var bmi = Math.round(weight / (height * height));
```

- Here, I store ‘weightInput’ in a new variable called ‘weight’

- Similarly, I store ‘heightInput’ in a new variable called ‘height’

- The formula to calculate BMI is weight divided by the square of height.

- so I created another variable and give it the name ‘bmi’ and applied the formula there.

- As you see, there is Math.round written there and you might be thinking what is it for?

- So, what Math. round will do is it will round off the output to its nearest integer.

- Let's say, the user enters weight as 65kg and height as 1.63 meters. So without Math.round we get the output like this // 24.4646016

- Now to round this off, we use Math.round and the same output looks something like this// 24.

**Method-2:- by using the function()**

```
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 codes for the ‘button’ element so that when the user enters height and weight and clicks the button, BMI gets displayed on the screen.

## STEP-4

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 will know how we can access the element from the document.

```
var valueThree = document.getElementById("btn");
```

- Here I created a variable and gave it the name of valueThree and then using the Id selector, I accessed the button from the HTML document.

- Now, what I want here is, when the user enters the values and clicks the button, it will show the BMI to the user. But, it's not that simple, we have to write some behind the scene codes for this to work.

- First, I have to make the button work. Whatever event is happening (in this case ‘click’), it should listen to that event, do the behind-the-scenes calculation, and then returns the output.

- So for that, I have to add a function called addEventListener to the Button which listens to the event that is happening there.

## STEP-5

**(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;

1) first is the ‘event’ that is happening, in this case, click event

2) 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.
**

## STEP-6

```
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, do 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.

## STEP-7

- Now as the user gets the BMI Values, I want to give specific messages to the user according to the BMI value they received.

- So, for that I used conditionals.

- I covered the [conditionals](https://shashnode.hashnode.dev/conditionals-in-javascript) in my previous blog so check that out before reading the below codes.

```
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, comment, and do follow me on Twitter, medium, and DevTo.

- Make sure to leave your important feedback, so that I can improve my future blogs.