Creating a BMI Calculator from Scratch with HTML, CSS, and JavaScript

Faraz

By Faraz -

Learn how to create a BMI calculator using HTML, CSS, and JavaScript.


Creating a BMI Calculator from Scratch with HTML, CSS, and JavaScript.jpg

Table of Contents

  1. Project Introduction
  2. HTML Code
  3. CSS Code
  4. JavaScript Code
  5. Preview
  6. Conclusion

Body Mass Index (BMI) serves as a vital tool in assessing one's health status by measuring body fat based on height and weight. Understanding BMI aids in comprehending weight-related health risks and enables individuals to make informed decisions about their lifestyle and wellness. In this tutorial, we'll delve into the creation of a BMI calculator using HTML, CSS, and JavaScript. By following along, you'll not only gain valuable insights into web development but also contribute to promoting health awareness through technology. Let's embark on this journey of learning and innovation together.

Join My Telegram Channel to Download the Project Source Code: Click Here

Prerequisites:

Before starting this tutorial, you should have a basic understanding of HTML, CSS, and JavaScript. Additionally, you will need a code editor such as Visual Studio Code or Sublime Text to write and save your code.

Source Code

Step 1 (HTML Code):

Begin by creating a basic HTML structure for the BMI calculator. Utilize input fields for height and weight, along with a button to calculate BMI.

Let's break down the HTML code:

1. <!DOCTYPE html>: This declaration specifies the document type and version of HTML being used.

2. <html lang="en">: The root element of the HTML document, indicating that the document is written in English.

3. <head>: This section contains meta-information about the document, such as character encoding, title, and links to external resources like CSS and JavaScript files.

  • <meta charset="UTF-8">: Specifies the character encoding of the document as UTF-8, which supports a wide range of characters.
  • <meta http-equiv="X-UA-Compatible" content="IE=edge">: Instructs Internet Explorer to use the latest rendering engine available.
  • <meta name="viewport" content="width=device-width, initial-scale=1.0">: Sets the viewport properties for responsive design, ensuring proper scaling on various devices.
  • <title>BMI Calculator</title>: Sets the title of the webpage displayed in the browser tab.
  • <link rel="stylesheet" href="styles.css">: Links an external CSS file named "styles.css" to style the HTML elements.

4. <body>: The main content of the webpage.

5. <form name="bmiForm">: A form element with the name "bmiForm" used for collecting input data.

6. Inside the form, there's a <div> with the class "bmi-calculator" containing the BMI calculator interface.

  • <h1>: Displays the heading "Calculate your BMI".
  • Two <div> elements with classes "bmi-calculator-weight" and "bmi-calculator-height" represent sections for inputting weight and height, respectively.
  • Each section contains an input element of type "range" for selecting values via a slider, and an input element of type "number" for direct input, along with corresponding labels.
  • <input class="gumb" type="button" value="Calculate" onclick="calculateBmi()">: A button triggering the calculation of BMI when clicked.
  • <span id="yourbmi">: A span element to display the calculated BMI value.
  • <p> elements for displaying messages.

7. <script src="script.js"></script>: Links an external JavaScript file named "script.js" for implementing functionality such as BMI calculation and user interaction.

Step 2 (CSS Code):

Enhance the visual appeal and user experience of the BMI calculator using CSS. Apply styles to input fields, buttons, and result displays to make it intuitive and attractive.

Let's break down the CSS code:

1. @import url('.....');: Imports the Google Fonts stylesheet for the Roboto font family with various weights (400, 500, 700) to be used throughout the webpage.

2. :root: Defines global CSS variables for consistent color usage throughout the document.

3. *: Applies CSS box-sizing reset to all elements, removing default padding and margin.

4. h1: Styles the heading element to be centered with specific margins.

5. html, body: Styles the HTML and body elements to occupy the full height and width of the viewport, sets the background color, and specifies the default text color.

6. .bmi-calculator: Styles the container for the BMI calculator with a specific border, border radius, box-shadow, padding, margin, height, and background color.

7. .bmi-calculator-weight, .bmi-calculator-height: Styles the sections for weight and height inputs with specific margins and width.

8. .weight-slider, .height-slider: Styles the slider input elements with a specific width, height, border-radius, and background color.

9. input[type=range]: Styles the slider input elements further, removing default appearances and specifying cursor behavior.

10. input[type=range]::-webkit-slider-thumb, input[type=range]::-moz-range-thumb, input[type=range]::-ms-thumb: Styles the slider thumb for different browsers with specific appearances, sizes, colors, and cursor behavior.

11. input[type=number]: Styles the number input elements with specific appearances, sizes, colors, margins, text alignment, font-family, and font-size.

12. .gumb: Styles the button element with specific text alignment, font-size, color, width, margin, border-radius, padding, transition, border, background color, text transformation, and cursor behavior. Also, specifies the hover effect.

13. @media only screen and (max-width: 325px): Defines responsive styles for screens with a maximum width of 325px, adjusting the height of the BMI calculator and font size of the heading.

@import url('https://fonts.googleapis.com/css?family=Roboto:400,500,700&display=swap');

:root {
  --background-color: #f6f6f6;
  --vigo-color: #B300B3;
  --slider-color: #A3A3A3;
  --input-number-color: #EBEBEB;
}

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

h1 {
  text-align: center;
  margin-left: 0.2em;
  margin-right: 0.2em;
  margin-bottom: 0.9em;
}

html,
body {
  height: 100%; width: 100%;
  margin: 0; padding: 0;
  background-color: var(--background-color);
  color: black;
}

body {
  display: flex;
  justify-content: center;
  align-items: center;
  font-family: 'Roboto', sans-serif;
}

.bmi-calculator {
  border: 5px solid white;
  border-radius: 10px;
  box-shadow: rgba(17, 12, 46, 0.15) 0px 48px 100px 0px;
  padding: 3em;
  margin: 2em;
  height: 520px;
  background-color: white;
}

.bmi-calculator-weight, .bmi-calculator-height {
  margin-bottom: 2.2em;
  width: 100%;
}

.weight-slider, .height-slider {
  width: 100%;
  height: 1px;
  border-radius: 10px;
  background: var(--slider-color); 
  outline: none; 
}

input[type=range] {
  -moz-appearance: none; 
  -webkit-appearance: none;
  appearance: none;
  cursor: pointer;
}

input[type=range]:focus {
  outline: none; 
}
input[type=range]::-ms-track {
  width: 100%;
  cursor: pointer;
}

input[type=range]::-webkit-slider-thumb {
  -webkit-appearance: none;
  border: 2.5px solid var(--vigo-color);
  height: 20px;
  width: 20px;
  border-radius: 40px;
  background: white;
  cursor: pointer;
  margin-top: 0px; 
}

input[type=range]::-moz-range-thumb {
  border: 2.5px solid var(--vigo-color);
  height: 20px;
  width: 20px;
  border-radius: 40px;
  background: white;
  cursor: pointer;
}

input[type=range]::-ms-thumb {
  border: 2.5px solid var(--vigo-color);
  height: 20px;
  width: 20px;
  border-radius: 40px;
  background: white;
  cursor: pointer;
}

input[type=number] {
  -moz-appearance: none; 
  -webkit-appearance: none;
  cursor: pointer;
  background: var(--input-number-color);
  border-style: none;
  height: 30px;
  width: 60px;
  margin-left: 20px;
  margin-right: 10px;
  text-align: right;
  font-family: 'Roboto', sans-serif;
  font-size: 1.5em;
}

input[type=number]:focus {
  outline: none; 
}

.gumb {
  text-align: center;
  font-size: 1em;
  color: white;
  width: 100%;
  margin-bottom: 10px;
  border-radius: 5px;
  padding: 11px 32px;
  transition: .2s;
  border: none;
  background-color: var(--vigo-color);
  text-transform: uppercase;
  cursor: pointer;
}
.gumb:hover{
  opacity: .8;
}

@media only screen and (max-width: 325px) {
  .bmi-calculator {
    height: 560px;
  }
  
  h1 {
    font-size: 1.5em;
  }
} 

Step 3 (JavaScript Code):

Write JavaScript code to calculate BMI based on the input provided by the user. Utilize the BMI formula: BMI = weight (kg) / (height (m))^2.

Let's break down the JavaScript code:

1. Accessing DOM Elements:

  • let weightSlider = document.getElementById("myWeight");: Retrieves the weight slider element from the DOM.
  • let weightOutput = document.getElementById("inputWeight");: Retrieves the weight output element from the DOM.
  • let heightSlider = document.getElementById("myHeight");: Retrieves the height slider element from the DOM.
  • let heightOutput = document.getElementById("inputHeight");: Retrieves the height output element from the DOM.

2. Setting Initial Values:

  • Sets the initial values of the weight and height outputs to the corresponding slider values.

3. Updating Slider Outputs:

  • Updates the weight and height outputs as the slider values change by listening for the input event on the sliders.

4. Function Declarations:

  • showValWeight(newVal): Updates the weight slider value based on user input.
  • showValHeight(newVal): Updates the height slider value based on user input.
  • updateValueWeight(e): Updates the weight output value based on the slider input.
  • updateValueHeight(e): Updates the height output value based on the slider input.

5. BMI Calculation:

  • calculateBmi(): Calculates the BMI using the weight and height values entered by the user.
  • Retrieves the weight and height values from the form.
  • Calculates the BMI using the formula BMI = weight / (height^2).
  • Displays the calculated BMI rounded to one decimal place.
  • Provides an evaluation message based on the calculated BMI:
  • If BMI is greater than 26, it suggests starting a workout.
let weightSlider = document.getElementById("myWeight");
let weightOutput = document.getElementById("inputWeight");

let heightSlider = document.getElementById("myHeight");
let heightOutput = document.getElementById("inputHeight");

weightOutput.innerHTML = weightSlider.value;
heightOutput.innerHTML = heightSlider.value;

weightSlider.oninput = function () {
  weightOutput.innerHTML = this.value;
}
heightSlider.oninput = function () {
  heightOutput.innerHTML = this.value;
}

function showValWeight(newVal) {
  weightSlider.value=newVal;
};

function showValHeight(newVal) {
  heightSlider.value=newVal;
};

weightSlider.addEventListener("input", updateValueWeight);
heightSlider.addEventListener("input", updateValueHeight);
function updateValueWeight(e) {
  weightOutput.value = e.srcElement.value;
}
function updateValueHeight(e) {
  heightOutput.value = e.srcElement.value;
}

function calculateBmi() {
  let weight = document.bmiForm.realweight.value;
  let height = (document.bmiForm.realheight.value)/100;
  let realbmi = (weight)/Math.pow(height, 2);
  let realbmiOutput = document.getElementById("yourbmi");
  let messageOutput = document.getElementById("evaluationMessage");
  let roundedBmi = realbmi.toFixed(1);
  messageOutput.innerHTML = ""; 
  realbmiOutput.innerHTML = " " + roundedBmi; 
  if (roundedBmi > 26) {
    messageOutput.innerHTML = "<br>Start workout";
  } 
}

Final Output:

Creating a BMI Calculator from Scratch with HTML, CSS, and JavaScript.gif

Conclusion:

Congratulations! You've completed the journey of building a BMI calculator using HTML, CSS, and JavaScript. By mastering this project, you've not only honed your web development skills but also contributed to promoting health awareness. Remember, the knowledge and experience gained from this tutorial are valuable assets in your coding journey. Keep exploring, learning, and innovating as you continue to make a positive impact through technology.

That’s a wrap!

I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee.

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post