Contents:

Course with employment: “Profession Front-end Developer"
Learn MoreBody Mass Index (BMI) is an important indicator that allows you to evaluate the ratio of a person's weight to height. It helps determine whether a person is within a healthy weight range or whether they need to think about adjusting their diet. Using BMI, you can easily understand whether you should indulge in another serving of your favorite dessert or whether it is better to temporarily abstain from excesses to maintain optimal health.
In this article, we will develop a simple Body Mass Index (BMI) calculator from scratch. We will create an HTML form for data entry, write a JavaScript script for calculations, and include CSS styles for design. All elements will function in the browser; just open the HTML file to use the calculator.
- What We Will Do
- Step One. Preparing the Development Environment
- Step Two. Create a project folder
- Step three. Create the interface markup
- Step four. Improve the appearance
- Step five. Add logic
- Step six. Test the application
What we will do
Calculating the body mass index (BMI) is very simple: you need to divide your body weight in kilograms by the square of your height in meters. This index is also known as the Quetelet index, named after the Belgian scientist Adolphe Quetelet, who first introduced this term. BMI is an important tool for assessing health and determining the ratio of a person's weight to height.
The calculator will be created using HTML, JavaScript, and CSS. In HTML, we will create the interface markup, placing all the necessary elements for functionality. JavaScript will be responsible for the application logic, including calculating the Quetelet index and other functions. CSS will give your application an aesthetic look, providing a stylish design. As a result, we will get a modern and functional calculator.

Preparing the development environment
Any modern code editor is ideal for developing in HTML, CSS, and JavaScript, but we We recommend using Visual Studio Code. This editor is one of the most popular due to its user-friendly functionality. It's completely free and compatible with Windows, macOS, and Linux operating systems. Visual Studio Code provides the ability to easily customize for various tasks due to the many available extensions, which makes it an excellent choice for web developers.

Read also:
Visual Studio Code: installation, configuration, Russian language support, and hotkeys
Visual Studio Code is a powerful and popular text editor, which is widely used by developers for writing code. To get started with Visual Studio Code, you need to complete a few steps: install the editor, customize it to suit your needs, localize the interface to Russian, and learn the basic hotkeys to increase your productivity.
To install Visual Studio Code, simply visit the official website and download the latest version for your operating system. The installation process is intuitive and does not require any additional knowledge.
Customizing Visual Studio Code allows you to tailor the editor to your individual preferences. You can change the design theme, install extensions for different programming languages, and configure auto-completion settings. This will help you create a comfortable working environment.
Russification of Visual Studio Code is carried out by installing a special language pack. To do this, open the extensions section, find the Russian language pack, and install it. After this, the editor interface will be available in Russian, which will significantly simplify the work for Russian-speaking users.
Knowledge of hotkeys in Visual Studio Code significantly speeds up the development process. Basic keyboard shortcuts include copying (Ctrl+C), pasting (Ctrl+V), saving a file (Ctrl+S), and quickly switching between files (Ctrl+Tab). Knowing the full list of keyboard shortcuts will help you work faster and more efficiently.
Thus, installing, configuring, localizing, and using keyboard shortcuts in Visual Studio Code make this editor the optimal tool for developers, allowing you to focus on your code and increase productivity.
To simplify working with HTML files, we recommend installing the Live Preview extension. This extension allows you to open your web page in a browser directly from the editor and automatically refresh it whenever you change the code. This significantly speeds up the development and testing process, allowing you to instantly see the results of your edits.
After launching the editor, go to the Extensions tab by clicking the icon consisting of four squares located in the sidebar. This will allow you to access additional features and tools that can improve your workflow.

Enter your query «Live Preview» in the search bar.
Select the Microsoft extension and click the install button. This will add the necessary features and improve the functionality of your app. Make sure you select the latest extension that meets your needs.

After installing the extension, a button for starting the server will appear in the bottom panel of the editor. When clicked, the extension opens the HTML page in your browser and begins tracking all code changes in real time. This allows you to instantly see the results of your edits and improves your web development process.
No additional extensions for HTML, CSS, or JavaScript are required, as VS Code provides built-in support for these languages. This allows developers to get started immediately without the need to install additional tools. With VS Code, you get access to powerful editing features like syntax highlighting, code completion, and version control integration, making web development much easier.
- Syntax highlighting,
- Code completion,
- Document structure navigation,
- Inline tooltips and documentation.

Creating a project folder
First, you need to create the necessary files. Before you begin, it is recommended to create a folder with a name, for example, bmi-calculator, in a convenient location on your computer.
Inside it, create three empty files.
- index.html - for marking up the application interface;
- style.css - application styles that define its appearance;
- script.js - for describing the calculator logic in JavaScript.
Now everything is ready to start developing the application.
Making the interface markup
The development environment is configured, and the project folder is created. Now you can move on to the layout. Before you begin writing HTML, it's important to determine what elements will be needed to create the calculator and what they are used for. Properly planning the HTML structure will help ensure the calculator's functionality and usability. It's important to consider that each element should fulfill its intended purpose, whether it's buttons, input fields, or result display areas. This will not only simplify the development process but also improve the user experience.
To calculate the body mass index (BMI), you need to enter two parameters: weight and height. The user enters this data manually, so two input fields are required: one for weight and one for height. Correctly calculating the BMI allows you to assess your health and identify potential problems associated with being overweight or underweight.
To ensure the clarity of the interface, we will add labels using tags next to each input field. These labels will serve as hints, indicating to the user what information needs to be entered. This will improve the user experience and make interaction with the interface more intuitive.
First, we will need a button that initiates the calculation process.
The calculation result will be presented on the page using two HTML tags. This will allow for effective data visualization and improve user perception of the information. Correct use of tags will ensure the structure of the content and improve its SEO optimization, which in turn can positively impact the visibility of the page in search engines.
- one will display the numerical value of BMI;
- the other - a text category: for example, "normal weight" or "overweight".
All of these elements will be placed inside a container. This will ensure their organization and ease of further work. The container will help improve the page structure and optimize content loading, which will have a positive impact on user experience and SEO optimization.

At the current stage, the application has A minimalist look, consisting only of text and input fields. This is perfectly acceptable, as the HTML code has already been prepared, and the CSS file has been included, although it lacks styles yet. The next step is to add some styling, which will improve the interface's appearance and make it more appealing to users. Optimizing the visual presentation of your app is important for enhancing user experience and increasing engagement.

Each input field has a hint specified using the placeholder attribute. The type=»number» attribute specifies that the field is intended exclusively for entering numeric values, which prevents the possibility of entering text information. Using the placeholder attribute improves the user interface, making it more understandable and convenient for users. Properly configuring input fields with the appropriate attributes helps to improve the quality of the data entered by users.
Clicking the button activates the calculate() function, which performs the calculation.
The results are presented in two blocks, which are located under the button.
- the numeric BMI value is displayed in the element with the .bmi class;
- the text interpretation (for example, "Normal weight" or "Obesity") is displayed in the element with the .category class.
Styles are included using the <link> tag, and scripts are added using the <script> tag. Correctly including styles and scripts is a key element of web development, as it allows you to improve the appearance of a site and its functionality. Make sure that the paths to the files are specified correctly to avoid errors in the display and operation of your web resource.
Improving the appearance
Let's open the style.css file and start working on the visual design of the application. First of all, we will set basic styles for the body tag, defining the font, text alignment, and background color. This will create the basis for further styling and improve the user interface of your application. Correctly chosen styles will help make the content more readable and attractive.
- font-family determines the font family used;
- text-align aligns the content to the center of the page;
- background-color sets the background color.
To change the color of the heading and subheading in HTML, use the color property. This property allows you to set the desired text color, improving the visual perception of content and increasing its readability. The right color choice helps highlight important information and attract visitors' attention. Use CSS to style headings to make them more appealing and consistent with the overall style of your website.
Of course, I can help you edit the text. Please provide the source text you would like to rework.

Now you need to design the area in which all the calculator elements will be placed. This process involves creating a structured and user-friendly interface that will ensure users can easily interact with the tool. It's important to keep in mind that the design should be intuitive, ensuring each element of the calculator is easily accessible and noticeable. Use clear visual distinctions and appropriate colors to enhance comprehension. It's also worth considering the responsiveness of the design to ensure the calculator displays correctly on various devices.
In this example, we customize the background color using the background-color property, set internal margins using padding, create rounded corners using border-radius, and add a subtle shadow using box-shadow. The display: inline-block property allows the element to behave like a block element while taking up only the necessary width for its content. This combination of properties helps create a stylish and functional design for web page elements, ensuring their visual appeal and ease of use.
As a result, you'll get a neat container that will fit perfectly into the overall design of your web project. Proper container design not only improves visual perception but also facilitates navigation. Using modern technologies and HTML standards helps create a container that is responsive and functional. This approach will provide users with a comfortable interaction with your site, which will positively affect its traffic and SEO positions.

Let's determine the location of text labels, input fields, and buttons. Proper placement of these elements on the page will improve the user experience and increase conversion. Text labels should be located close to the corresponding input fields so that users can easily understand what information to enter. Input fields should be arranged vertically or horizontally, depending on the page design. The action button should be prominent and visible to attract users' attention and facilitate completion of the target action.
This example uses the display property with the table-cell value, which allows elements such as label, input, and button to be arranged in a table. Each of these elements occupies a separate cell in a row, providing an organized and structured display. Additionally, the margin property allows you to set vertical padding between elements, which improves the appearance and ease of interaction with the form. Using these CSS properties allows you to create more organized and visually appealing interfaces.
The elements are placed compactly and evenly. This provides a neat and organized appearance, which helps improve the perception of information. Proper alignment of elements on the page facilitates easy navigation and improves the user experience. Optimizing the placement of elements also has a positive effect on SEO, since search engines prefer structured and organized pages.

Styling needs to be completed We set the button's background color, define the text color, remove the border using the border: none property, add padding, and round the corners. When hovered, the cursor changes to a pointer. We also apply a hover effect, which changes the button's color on hover, adding interactivity and improving the user experience. As a result, we'll create high-quality, optimized content that meets modern SEO standards. This will increase your website's visibility in search engines and attract your target audience. Text optimization includes keyword usage, improving structure and readability, and creating unique and informative content. All of these factors contribute to increased traffic and interest in your product or service. Striving for high-quality content will allow you to stand out from the competition and attract more clients.

Now everything matches the plan.
Here is the final CSS code:
«`css
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}
h1 {
color: #333;
font-size: 24px;
margin-bottom: 20px;
}
p {
color: #666;
line-height: 1.5;
margin-bottom: 15px;
}
a {
color: #007BFF;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
.container {
max-width: 1200px;
margin: auto;
padding: 20px;
}
.header {
background-color: #f8f9fa;
padding: 15px;
text-align: center;
}
.footer {
background-color: #f1f1f1;
padding: 10px;
text-align: center;
}
.button {
background-color: #007BFF;
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
}
.button:hover {
background-color: #0056b3;
}
«`
This CSS code provides basic styling for a web page, including the design of text, links, buttons, and containers. It is suitable for creating a modern and user-friendly interface, improving visual perception and user interaction with the content.
Now we will move on to developing the calculator logic. This stage involves defining the main functions and algorithms that will be used to perform calculations. It is important to consider all possible use cases to ensure the accuracy and reliability of the calculator. Pay attention to the processing of user input and the implementation of mathematical operations. Effective calculator logic should be intuitive and provide quick results, which will positively impact the user experience.
Adding Logic
We will teach our application to calculate body mass index (BMI) and correctly interpret the results.
We will create the basic structure of a function called calculate(). This function will be called when the user clicks the "Calculate" button.

Read also:
Functions in JavaScript: Declaring, Calling, and Using Without Errors
JavaScript functions are the fundamental building block of programming in this language. They allow you to organize your code, making it more readable and reusable. It is important to know how to properly declare, call, and use functions to avoid common mistakes.
There are several ways to declare a function in JavaScript. One of the most common methods is using the «function» keyword. For example, you could declare a function like this:
function FunctionName() {
// function code
}
You can also use functional expressions and arrow functions. Function expressions look like this:
const FunctionName = function() {
// function code
};
Arrow functions, introduced in ES6, have a more compact syntax:
const FunctionName = () => {
// function code
};
Once a function is declared, it can be called by simply providing the function name and adding parentheses:
functionName();
If the function takes parameters, they must be provided in parentheses. For example:
function addition(a, b) {
return a + b;
}
You can pass values with a function call:
addition(2, 3); // result is 5
When working with functions, it is important to be aware of execution context. JavaScript has multiple ways of binding context, which can lead to errors if you are not mindful of how and where functions are called.
Also, to avoid errors, you should use strict mode. You can do this by adding «use strict» to the beginning of your script or function. It helps identify problems in your code, such as the use of uninitialized variables.
Functions in JavaScript provide flexibility and power when building web applications. Understanding how to declare, call, and use them correctly will help you avoid common mistakes and make your code more efficient.
JavaScript allows you to modify the content of a web page by interacting with HTML elements. To do this, it needs to access specific elements, such as input fields, buttons, and containers that will display the result. This interaction allows you to dynamically update information on the page, improving the user experience and providing interactivity.
To accomplish this task, the document.querySelector command is used. This method allows you to select an element on a web page using CSS selectors. document.querySelector is a powerful tool for DOM manipulation, as it provides access to the first element found that matches the specified selector. Using this method, developers can efficiently access elements, change their properties, add events, and manipulate page content. Thus, the ability to select elements using document.querySelector greatly simplifies the development process and improves the user experience.
- document is the entire HTML page.
- querySelector() is a command that finds an element on the page by its class, tag, ID, or any other selector.
To access an input field with the weight class in JavaScript, you can use the document.querySelector method. For example, to get the element, you can write the following code:
const weightInput = document.querySelector(‘.weight’);
This code makes it easy to interact with the input field, change its values, or handle events. Using classes for selectors simplifies selecting elements on the page and makes the code more readable.
- «.weight» — is a CSS class selector (the dot indicates that we are searching by class).
- weightInput — a variable in which we store the found element.
We can also extract other elements.
Now we will extract the values the user entered in the "Weight" and "Height" fields. This data is necessary for further calculations and analysis. The obtained values will allow us to provide more accurate results and recommendations.
When the user enters data into the text field, it is stored as plain text. To perform mathematical operations such as division and exponentiation, it is necessary to convert this text to a numeric format. For this, the parseFloat() function is used, which allows you to convert a string to a floating-point number. This conversion is an important step for performing further calculations.
- weightInput.value is what the user entered in the "Weight" field.
- heightInput.value is what they entered in the "Height" field.
- parseFloat() — converts text to a number, including decimal fractions.
Before validating user input, you need to make sure that they have indeed filled in the required fields. In case the user accidentally clicked the "Calculate" button without entering information, a notification should be displayed asking them to enter the data. In addition, the cursor should be positioned in the field that requires filling in to ensure convenience and speed up the information entry process.
isNaN() is a function that determines whether a value is a number. If the function returns true, it means that the entered data is either missing or contains an error. Using isNaN() allows you to efficiently process user input and prevent errors in calculations involving numerical data.
Checking for growth is an important process that helps identify opportunities for improvement and optimization. This stage involves analyzing current indicators and assessing the factors that facilitate or hinder growth. Regular checking allows you not only to track changes but also to adjust your strategy based on the data obtained. Using various analytical methods, such as SWOT analysis or competitor analysis, contributes to a deeper understanding of the situation and helps develop effective solutions to achieve goals. Incorporating regular checks into business processes ensures sustainable growth and development of the company.
If the entered data is correct, we will calculate your body mass index. Body mass index (BMI) is an important indicator that helps assess the relationship between a person's weight and height. Correctly calculating BMI allows you to determine whether your weight is normal or if there is a risk of becoming overweight, underweight, or obese. To do this, you must enter accurate height and weight values. After receiving the results, you will be able to draw conclusions about your health and, if necessary, consult a specialist.
- divide the weight in kilograms by the square of the height in meters;
- height / 100 — convert centimeters to meters;
- ** 2 — square the height.
Create a category variable, which will later contain text explaining the result. This variable will help structure the information and improve the understanding of the output data.
Now we set the value of the category variable depending on the value of the bmi variable. After the user has entered the data and we have calculated their body mass index (BMI), we need to determine which category they belong to: underweight, normal weight, overweight, or obese. To do this, we use the if…else conditional construct, which allows you to perform different actions depending on the value of the bmi variable. This is an important step in analyzing a user's health status.
Here's how it works:
Each condition compares the body mass index (BMI) value to the set thresholds. If the value meets the specified criteria, a textual interpretation of the status is assigned to the category variable. Additionally, the calculator background (.calculator) changes color depending on the resulting category. This helps visually highlight the results and makes it easier to understand the user's health status.
- light red — if underweight;
- green — if normal weight;
- bright red — if overweight;
- dark red — if obese.

Redesigned text:
Explore our article for valuable information. We offer in-depth analysis and practical recommendations to help you better understand the topic. Our goal is to provide readers with quality content tailored to their needs. By delving into the material, you will expand your knowledge and find useful tips. Don't miss the opportunity to learn more about key aspects that can impact your life or business.
Read also:
Conditional operators in JavaScript: if, else, and switch - programming basics for beginners. These constructs allow you to perform different actions depending on the specified conditions. Understanding how they work is key in JavaScript development.
The if statement is used to test a condition and execute a block of code if the condition is true. If the condition is false, you can use the else statement to execute an alternative block of code. For example, you can check whether a number is positive and display an appropriate message.
The switch statement is a more convenient way to handle multiple conditions. It allows you to compare one value with several possible options. This is especially useful when you need to test the same expression against several different values.
When using conditional statements, it is important to ensure correct syntax and logic. Errors in conditional expressions can lead to incorrect execution of the code. It is recommended to use the console for debugging and testing conditions.
Knowledge and correct use of if, else, and switch statements will significantly simplify the process of writing code and make it more readable. By mastering these constructs, you will be able to create more complex and functional applications in JavaScript.
Here is the final version of the function:
The calculate() function performs several tasks: it receives data, validates it, calculates the body mass index (BMI), and formats the result. Although this approach works correctly, the code becomes unwieldy, making it difficult to read and maintain. To make the code more convenient to work with, we will split it into several smaller functions. This will make it easier to navigate the code and make future changes easier.
This function is designed to search for height and weight input fields, as well as to retrieve the entered values and check their correctness. If an error is detected, a message is displayed, and the function returns null.
The function calculates the body mass index (BMI) based on the entered parameters: weight and height. BMI is an important indicator that helps assess health and determine the ratio of body weight to height. Using this function, you can quickly and accurately obtain a BMI value, which will help you monitor your health and fitness.
The function returns an object containing a category and a background color depending on the body mass index (BMI) value. Correct interpretation of BMI allows you to classify health status and visually highlight the corresponding categories using color schemes.
The main function has been simplified and made more understandable. It now calls helper functions, collects the obtained results, and displays them on the page. This improvement allows you to manage your code more efficiently and makes it easier to maintain.
The complete code will be presented as follows:
Testing the application
Now that the code is complete, you can test the calculator directly in the built-in browser using the Live Preview extension. This will allow you to instantly see the results of your code, making the development process more efficient. Don't miss the opportunity to test the calculator's functionality in real time to ensure its correct operation and ease of use.
Let's consider a basic scenario: if both fields are left empty and the user clicks the button, the application will immediately notify them to enter a weight value. The cursor will automatically move to the weight input field, making it easier to interact with the application.

Scenario two: we enter the weight value, while the height field remains empty. In this case, the system will not be able to process the data correctly and will return an error. To obtain accurate results and recommendations, please fill in both weight and height fields. This will allow the system to provide the necessary calculations and recommendations that match your parameters.

After clicking the button, the message "Enter your height!" will appear. The cursor will automatically move to the corresponding input field. Enter your height and click the button to continue.

Now we will enter the values of weight and height, and then click the button. The app will calculate your body mass index and display the result. If your BMI is within the normal range, the calculator's background will turn green, and a message will notify you of your normal weight. This will allow users to quickly assess their physical condition and take the necessary measures to maintain health.
Let's change the parameters, for example, reduce the height.

Body Mass Index (BMI) will increase, and the page background will change to red. A message on the screen will indicate that the user is obese.
The calculator is functioning correctly, as it correctly processes the entered data, calculates the body mass index (BMI), and interprets the results accurately. This confirms its reliability and accuracy in calculations.
The calculator can be run not only through Live Preview, but also directly in the browser. To do this, follow these steps. First, ensure you have the required web server installed to ensure the correct operation of the application. Then, open your browser and enter the path to the calculator file. This will allow you to use its functionality without the need for a development environment. Launching the calculator this way allows you to evaluate its performance and usability in real-world conditions, which is especially important for users.
- Find the index.html file in the project folder.
- Double-click on it - it will open in the browser by default.
- If a text editor, for example, opens instead of a browser, right-click on the file and select "Open with", then select the desired browser (for example, Google Chrome or Firefox).
A working calculator in the Firefox browser may look like this:

Learn more about coding and programming in our Telegram channel. Subscribe to stay up-to-date with useful information and interesting content!
Read also:
- What is JavaScript and why is it needed?
- How to make a simple slider using HTML, CSS, and JavaScript
- Cycles in JavaScript: What they are, how they differ, and why they are needed
- Conditional operators, if, else, and switch in JavaScript: where to start and how to avoid mistakes
Learn more about coding and programming in our Telegram channel. Subscribe to stay up-to-date with relevant content and helpful tips.

