Building A B.M.I Calculator using Typescript
Tags: webdev, tutorial, typescript, programming
Published: 2023-08-19 06:59:14

In today's tech driven world, health and wellness are a paramount importance so is the ability to leverage programming to aid in various aspects of our lives. In this article, we will embark on an exciting journey to create a Body Mass Index calculator using Typescript-a powerful and statically-typed superset of Javascript. Understanding BMI is crucial for assessing one's health and by the end of this tutorial, you will have a functional tool that can help users calculate their BMI based on their weight and height.

## What is BMI
The Body Mass Index is a measure that uses your height and weight to work out if your weight is healthy. The calculation is a person's weight in kg divided by the square of height in meters.
If your BMI is;

- Below 18.5- underweight range.

- Between 28.5 and 24.9- you are in the healthy weight range.

- Between 25 and 29.9- you are in the overweight range.

- 30 or over- you are in the obese range.

## Setting up the project
Before you begin ensure you have [Node.js](https://nodejs.org/en) and [Typescript](https://www.typescriptlang.org/download) installed.

Create a project folder called bmi and the bmi folder should have build and src folders. In the build folder it should contain HTML and CSS files and in the src folder it should contain a Typescript file.

Go to the terminal and type;

```
tsc --init
```
This creates a typescript configuration file named tsconfig.json which specifies how Typescript should compile your code and what settings to use.
Open it and make the following changes;

```
"rootDir": "./src"
"outDir": "./build/JS"
"include":["src"]
```
When you run the Typescript compiler, it will look for Typescript files in the src directory compile them and place the compiled files in the build/JS directory.
The include option specifies which files should be included in the compilation process, so Typescript will include all Typescript files within the src directory.

After that, type this into the terminal;

```
tsc -watch
```
This watches for changes in your Typescript files and recompiles them as needed.
This is the folder structure;

![folder structure](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nhdoa8n81iuakj3tpt2g.PNG)

## Create the HTML file

```
<div class="container">
        <h1>BMI CALCULATOR</h1>

        <!-- displays the calculated bmi value and its category-->
        <div class="display">
            <p id="result">20.0</p>
            <p id="category">Normal Weight</p>
        </div>

        <!--a range slider for selecting the weight-->
        <div class="row">
            <input type="range" min="20" max="200" value="20" id="weight" oninput="calculate()">
            <span id="weight-val">20kg</span>
        </div>

        <!--a range slider for selecting the height-->
        <div class="row">
            <input type="range" min="100" max="250" value="100" id="height" oninput="calculate()">
            <span id="height-val">100cm</span>
        </div>
    </div>
    <script src="/build/JS/bmi.js"></script>
```
This HTML code provides a user interface for a BMI calculator where users can input their weight and height using range inputs and a display area for showing the calculated BMI value and its category.

## Create a Typescript file.

```
//the void type does not return any value
function calculate():void{
    //stores the calculated BMI as a string
    var bmi:string;
    //holds the reference to an HTML element with the id result
    var result = document.getElementById("result") as HTMLElement;
    //the height value is extracted from the input element and the value is converted into an integer
    var height= parseInt((document.getElementById("height") as HTMLInputElement).value);
    //the weight value is extracted from the input element and the value is converted into an integer
    var weight =parseInt((document.getElementById("weight") as HTMLInputElement).value);

    //displays weight and height values
    document.getElementById("weight-val")!.textContent = weight + "kg";
    document.getElementById("height-val")!.textContent = height + "cm";

    //calculate the BMI using the height and weight values and toFixed ensures the BMI is rounded to one decimal place 
    bmi = (weight / Math.pow(height / 100, 2)).toFixed(1);
    result.textContent = bmi;
    let category: string;

    //determines the BMI category based on the calculated BMI value
    if(parseFloat(bmi)< 18.5){
        category = "Underweight 😔";
        result.style.color= "#ffc44d";
        //checks if it is between 18.5 and 24.9
    } else if (parseFloat(bmi) >= 18.5 && parseFloat(bmi) <= 24.9){
        category = "Normal weight 🤩";
        result.style.color = "#0be881";
        //checks if it is between 25 and 29.9
    } else if (parseFloat(bmi) >= 25 && parseFloat(bmi) <= 29.9){
        category = "Overweight 😮";
        result.style.color = "#ff884d";
    } else {
        category = "Obese 😱";
        result.style.color = "#ff5e57";
    }

    //display BMI category
    document.getElementById("category")!.textContent = category;
}
```
This Typescript code calculates the BMI based on user inputs, updates the displayed values and categories on the webpage and adjusts the text color based on the calculated BMI category. This code enables the BMI calculator interface to dynamically update as users interact with the height and weight sliders.

## Create the CSS code
Style the BMI calculator.
```
*, *::before, *::after{
    padding: 0;
    margin: 0;
    box-sizing: border-box;
}

body{
    height: 100vh;
    font-family: monospace;
    background-color: #3D5B59;
}

.container{
    background-color: #bd8c92;
    padding: 10px 40px;
    width: 350px;
    margin: 50px auto;
    border-radius: 5px;
}

.container h1{
    text-align: center;
    font-size: 23px;
    margin: 20px auto;
    font-family: cursive;
}

.row{
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.display{
    margin-bottom: 30px;
    margin-top: 30px;
    font-size: 20px;
}

#result, #category{
    text-align: center;
    margin-right: 10px;
    font-weight: 1000;
}

.row span{
    margin-bottom: 20px;
    font-size: 20px;
    margin-right: 15px;
}

input[type=range]{
    width: 50%;
    margin-bottom: 20px;
    height: 5px;
    appearance: none;
    background-color: black;
    border-radius: 5px;
    outline: none;
    cursor: pointer;
}

input[type="range"]::-webkit-slider-thumb{
    appearance: none;
    height: 15px;
    Width: 15px;
    background-color: #B5E5CF;
    cursor: pointer;
    border-radius: 100%;
} 
```
You can check out the code on my [github](https://github.com/Pauline-Oraro/bmi-typescript-calculator).