Weight Loss Calculator using JavaScript

Weight Loss Calculator using JavaScript
Code Snippet:Fitness form / Weight Loss Calculator
Author: Darren Colson
Published: January 19, 2024
Last Updated: January 22, 2024
Downloads: 688
License: MIT
Edit Code online: View on CodePen
Read More

A web-based weight loss calculator that helps you determine essential information for your weight management journey. It collects data on your gender, age, weight, height, and activity level. It calculates your Basal Metabolic Rate (BMR), Calories Burned, Body Mass Index (BMI), and Weight Category.

The “calculateBasal” function computes your BMR based on your gender, age, weight, and height. The “calculatePal” function calculates your daily calorie needs based on your activity level. “calculateBmi” computes your BMI, and “weightCat” determines your weight category. The “eat” function helps estimate daily calorie intake for weight loss.

This code simplifies the process of understanding your calorie needs and BMI, making it a valuable tool for anyone looking to manage their weight effectively.

How to Create a Weight Loss Calculator Using JavaScript

1. First of all, load the Normalize CSS by adding the following CDN link into the head tag of your HTML document.

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">

2. Copy the following HTML code and paste it on your web project where you want to appear calculator. It provides the structure for the calculator, including form elements, labels, and placeholders for the results.

<div class="container">
  <h1>Weight loss Calculator</h1>
  <form name="basalForm" id="basalForm">

    <ul class="questions">
      <h2>Questions</h2>
      <li>Your Gender <select name="sex">
          <option value="male">Male</option>
          <option value="female">Female</option>
        </select></li>
      <li>Age (Years) <input type="number" name="age" maxlength="3" size="3" required></li>
      <li>Your weight (lbs)<input type="number" name="weight" maxlength="3" size="3" required></li>
      <li>Your Height (inches)<input type="number" name="height" maxlength="3" size="3" required></li>
      <li>Your Activity level (PAL)
        <select name="activityLevel">
          <option value="sedentary">Sedentary (less than 30min a week)</option>
          <option value="lightExercise">Light exercise (90min a week) </option>
          <option value="moderateExercise">Moderate exercise (aerobic exercise, 120min a week)</option>
          <option value="veryActive">Very active (150min a week)</option>
          <option value="extreme">Extreme (Athlete status)</option>
        </select>
      </li>
    </ul>
    <div class="buttons">
      <input type="reset" value="Reset" />
      <input type="button" value="Calculate calorie levels" onClick="calculateBasal(); calculatePal(); calculateBmi(); weightCat(); eat();" id="calculate">
    </div>

    <ul class="answers">
      <h2>Answers</h2>
      <li>Your body needs at rest during a typical day <input type="text" name="basal" size="12"></li>
      <li>Calories burned during a typical day<input type="text" name="pal" size="12"><cite>Based on your
          activity
          level (PAL)</cite></li>
      <li>Your body should lose (per day) approx. <input type="text" name="calLose" size="12"></li>

      <li>Your BMI (Body Mass Index) <input type="text" name="bmi" size="12"></li>
      <li>Your weight category <input type="text" name="weightCategory" size="12"></li>
    </ul>

  </form>

  <div class="message" id="message">
    If you lose 500 Kcals a day, you would lose about 1lb of weight a week.<br>

    BMI Formula = [Weight (lbs) / Height (inches)²] x 703 or Weight (kg) / Height (m) 2 <cite><a href="https://www.diabetes.co.uk/bmi.html">diabetes.co.uk</a></cite>
    <br>
    Example Input = 42yrs, 170lbs , 67inches
  </div>
  <!--message-->

</div> <!-- container-->

3. Now, use the following CSS code to style the basic interface for the calculator. You can customize the calculator’s appearance by modifying the CSS styles. Adjust the colors, fonts, and layout to match your website’s design.

*,
html,
body {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-size: 16px;
  font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}

body {
  width: 100%;
  height: 100%;
}

.container {
  padding: 3em;
}
.container form#basalForm {
  width: -webkit-max-content;
  width: -moz-max-content;
  width: max-content;
  height: -webkit-max-content;
  height: -moz-max-content;
  height: max-content;
  display: flex;
  flex-direction: column;
  padding: 20px;
}
.container form#basalForm input[type=button]#calculate {
  background-color: rgba(67, 126, 67, 0.616);
  color: #fff;
  font-weight: 600;
  padding: 8px 12px;
  margin: 20px 0px;
  cursor: pointer;
  border: none;
  border-radius: 2px;
}
.container form#basalForm input[type=button]#calculate:hover {
  background-color: rgba(67, 126, 67, 0.8);
}
.container form#basalForm input:invalid {
  background-color: rgba(240, 119, 119, 0.384);
}
.container form#basalForm input[type=reset] {
  background-color: rgba(238, 176, 176, 0.603);
  width: -webkit-max-content;
  width: -moz-max-content;
  width: max-content;
  color: darkslategray;
  padding: 2px 6px;
  margin: 20px 0px;
  border: none;
  border-radius: 2px;
  cursor: pointer;
}
.container form#basalForm input[type=reset]:hover {
  background-color: rgba(238, 176, 176, 0.9);
}
.container form#basalForm input[type=text] {
  padding-left: 8px;
  margin-left: 8px;
}
.container form#basalForm .buttons {
  display: flex;
  justify-content: space-between;
}
.container form#basalForm ul.questions li,
.container form#basalForm ul.answers li {
  list-style: none;
  width: 100%;
  display: flex;
  position: relative;
  justify-content: space-between;
  padding: 8px 0px;
  margin-right: 10px;
}
.container form#basalForm ul.questions li select,
.container form#basalForm ul.answers li select {
  min-width: 80px;
}
.container form#basalForm ul.questions li input,
.container form#basalForm ul.answers li input {
  min-width: 80px;
  max-width: -webkit-min-content;
  max-width: -moz-min-content;
  max-width: min-content;
  border: none;
  border-bottom: 1px solid grey;
}
.container form#basalForm ul.questions li cite,
.container form#basalForm ul.answers li cite {
  position: absolute;
  width: 100%;
  height: -webkit-max-content;
  height: -moz-max-content;
  height: max-content;
  left: 0;
  bottom: -8px;
  color: grey;
  font-size: 0.8em;
}

4. Finally, Copy the JavaScript code and paste it at the end of your HTML file, just before the closing </body> tag. This JavaScript code defines functions for calculating BMR, PAL, BMI, weight category, and daily calorie intake for weight loss.

function calculateBasal() {
    var sex = document.basalForm.sex.value;
    var age = document.basalForm.age.value;
    var weight = document.basalForm.weight.value;
    var height = document.basalForm.height.value;
    var activityLevel = document.basalForm.activityLevel.value;


    if (document.basalForm.sex.value == "female") {
        basal = 655 + (4.35 * weight) + (4.7 * height) - (4.7 * age);
        return document.basalForm.basal.value = basal.toFixed(2) + " Kcals";
    } else {
        basal = 66.47 + (6.23 * weight) + (12.7 * height) - (6.755 * age);
        return document.basalForm.basal.value = basal.toFixed(2) + " Kcals";
    };
}



function calculatePal() {
    var sex = document.basalForm.sex.value;
    var age = document.basalForm.age.value;
    var weight = document.basalForm.weight.value;
    var height = document.basalForm.height.value;
    var activityLevel = document.basalForm.activityLevel.value;


    if (document.basalForm.activityLevel.value == "sedentary") {
        activityLevel = 1.2
        var pal = basal * activityLevel;
        return document.basalForm.pal.value = pal.toFixed(2) + " Kcals";
    } else if (document.basalForm.activityLevel.value == "lightExercise") {
        activityLevel = 1.375
        var pal = basal * activityLevel;
        return document.basalForm.pal.value = pal.toFixed(2) + " Kcals";
    } else if (document.basalForm.activityLevel.value == "moderateExercise") {
        activityLevel = 1.55
        var pal = basal * activityLevel;
        return document.basalForm.pal.value = pal.toFixed(2) + " Kcals";
    } else if (document.basalForm.activityLevel.value == "veryActive") {
        activityLevel = 1.725
        var pal = basal * activityLevel;
        return document.basalForm.pal.value = pal.toFixed(2) + " Kcals";
    } else {
        activityLevel = 1.9
        var pal = basal * activityLevel;
        return document.basalForm.pal.value = pal.toFixed(2) + " Kcals";
    }
}

function calculateBmi() {
    var height = document.basalForm.height.value;
    var weight = document.basalForm.weight.value;
    var bmi = (weight / (height * height)) * 703;
    return document.basalForm.bmi.value = bmi.toFixed(2);
}

function weightCat() {
    bmi = document.basalForm.bmi.value;

    if (bmi > 39.9) {
        return document.basalForm.weightCategory.value = "Morbidly obese";
    } else if (bmi > 29.9) {
        return document.basalForm.weightCategory.value = "Obese";
    } else if (bmi > 24.9) {
        return document.basalForm.weightCategory.value = "Overweight";
    } else if (bmi > 18.5) {
        return document.basalForm.weightCategory.value = "Normal healthy";
    } else {
        return document.basalForm.weightCategory.value = "Underweight";
    };

};

function eat() {
    var pal = document.basalForm.pal.value;
    var palx = parseInt(pal, 10);
    console.log(palx);
    var basal = document.basalForm.basal.value;
    var basalx = parseInt(basal, 10);
    var calLose = palx - basalx;
    return document.basalForm.calLose.value = "- " + calLose + " Kcals";
}

That’s all! hopefully, you have successfully created a Weight Loss Calculator Using JavaScript. If you have any questions or suggestions, feel free to comment below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About CodeHim

Free Web Design Code & Scripts - CodeHim is one of the BEST developer websites that provide web designers and developers with a simple way to preview and download a variety of free code & scripts. All codes published on CodeHim are open source, distributed under OSD-compliant license which grants all the rights to use, study, change and share the software in modified and unmodified form. Before publishing, we test and review each code snippet to avoid errors, but we cannot warrant the full correctness of all content. All trademarks, trade names, logos, and icons are the property of their respective owners... find out more...

Please Rel0ad/PressF5 this page if you can't click the download/preview link

X