BMI Calculator Using HTML, CSS, JS with Full Source Code For Beginners

  • Body mass index (BMI) is a measure of body fat based on height and weight that applies to adult men and women.
  • This application will calculate BMI.

Source Code:

index.html

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="style.css"> <title>BMI Calculator</title> </head> <body> <div class="container"> <h1>BMI Calculator</h1> <form> <p><label>Height in CM: </label><input type="text" id="height"></p> <p><label>Weight in KG: </label><input type="text" id="weight"></p> <button>Calculate</button> <div id="results"></div> <div id="weight-guide"> <h3>BMI Weight Guide</h3> <p>Under Weight = Less than 18.6</p> <p>Normal Range = 18.6 and 24.9</p> <p>Overweight = Greater than 24.9</p> </div> </form> </div> </body> <script src="script.js"></script> </html>
Code language: HTML, XML (xml)

style.css

.container { width: 375px; height: 525px; margin-left: 350px; margin-top: 65px; background-color: yellow; padding-left: 30px; } #height, #weight { width: 150px; height: 25px; margin-top: 30px; } #weight-guide{ margin-left: 75px; margin-top: 25px; } #results{ font-size: 35px; margin-left: 90px; margin-top: 20px; color: blue; } button{ width: 150px; height: 35px; margin-left: 90px; margin-top: 25px; border-radius: 5px; border-style: none; background-color: blue; color: #fff; font-size: 25px; } h1{ padding-left: 15px; padding-top: 25px; }
Code language: CSS (css)

script.js

const form = document.querySelector('form'); form.addEventListener('submit', function(e){ e.preventDefault(); const height = parseInt(document.querySelector('#height').value); const weight = parseInt(document.querySelector('#weight').value); const results = document.querySelector('#results'); if((height === '') || (height < 0) || (isNaN(height))){ //NaN !== NaN results.innerHTML = "Please provide a valid height"; } else if (weight === '' || weight < 0 || isNaN(weight)){ results.innerHTML = "Please provide a valid weight"; } else { //calculate BMI const bmi = (weight / ((height*height)/10000)).toFixed(2); //display the results results.innerHTML = `<span>${bmi}</span>` } });
Code language: JavaScript (javascript)

Output:

Leave a Comment