Coding your first JavaScript application – BMI Calculator

Coding your first JavaScript application – BMI Calculator.

Error: BMI Calculator could not be displayed, please upgrade your browser.

         We already created a BMI (Body Mass Index) Calculator using Excel VBA last month. How difficult would it be to rewrite that calculator in JavaScript to embed it on any webpage for people to use? Not that difficult , thought I, remembering happy days of browsing the original, NOT corporate owned, HTML Goodies website in search of the coolest JS mouse-over effects, some 15 years ago. You can see the working calculator above of this post, but I would be lying saying that its creation was painless. Surely, “World’s Largest Web Development Site” provides more than enough reference material for all elements required: HTML and JavaScript, as well as optional, but handy styling language – CSS. However, tweaking my code and making it work, was a very time-consuming process. Looking at my final product and comparing it to top 10 Google search results for BMI Calculator makes it all worthwhile…. Not only it incorporates more enjoyable design, it is also equipped with error handling logic.

         I am a strong believer in learning by doing. More so, if we have a foundation to build from. My hope is that you will take the code provided , play with it, and make it your own. In the meantime, let’s walk through some specific code areas to get a better understanding of how this calculator actually works:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>BMI Calculator - Stay Healthy, learn your BMI score. Presented by Excel Strategies, LLC.</title>

<style type="text/css">
/*Formatting font sizes, colors and line spacing*/
h1 {font-size: 30px; color:maroon;line-height:0.5;}
h2 {font-size: 25px; color:#009933;line-height:0.5;}
h3 {font-size: 15px; color:#000066; font-family:"Comic Sans MS"; line-height:0.5;
h4 {font-size: 25px; color:maroon; font-weight:bold; line-height:0.1;}
h5 {font-size: 20px; color:#000066; font-family:"Comic Sans MS"; line-height:0.1;}
p.small {line-height: 10%;}

/*Formatting form size, shape, and color*/
form {width: 320px;
    margin-left: 80px;
    margin-top: 20px;
    border: 5px  double  #009933;
    border-radius: 3em;
    padding: 1em;
    background: #FCFCFC;}

/*Formatting textboxes*/
input, textarea {
    font: 1em sans-serif;
    width: 65px;
    box-sizing: border-box;
    background: 10px 10px 5px #FFFFD6;
    color: maroon;
    font-weight: bold;}
</style>
</head>

         My code comments should help you understand this code better. This section defines your HTML document and specifies CSS styling options for your form, form elements, subheadings fonts, and paragraph formatting. I will refer you to W3 Schools for further reference. I am not a designer, and you should be able to come up with your own unique design for this exercise. As you can see, I used this code to format font styles, colors, line spacing, etc. The most useful feature came with the form object, and border formatting specifically. I’m very impressed with the power of 1 or 2 simple CSS statements.

script type = "text/javascript">

/* BMI Calculator function*/
    function BMICalculate()
	
/* Accept input variables*/
    {
    var weight = document.getElementById('weight').value;
    var heightft = document.getElementById('heightft').value;
	
    /* Error Handling  for invalid data entered*/
   if (weight == "") {
                alert("Please enter your weight.");
				return;  }
   if (heightft == "") {
                alert("Please enter your height.");
				return;  }	
   if (weight < 0) {
                alert("Your weight can only be negative in Theoretical Physics..., NOT in real life.");
				return;  }
   if (weight < 30) {
                alert("Weighing " + weight  + " lbs, you must be a child, this is Adult BMI calculator!");
				return;  }
   if (weight > 1500) {
                alert("Do you really weigh " + weight + " pounds?!");
				return;  }
   if (heightft < 0) {
                alert("Your can not possibly have a negative height!");
				return;  }
   if (heightft < 3) {
                alert("Standing " + heightft +" feet tall, you must be a child, this is Adult BMI calculator!");
				return;   }
   if (heightft > 10) {
                alert("Are you really "  + heightft + " feet tall?!");
				return;  }
		
  /* Performing calculations */	
    var heightin = document.getElementById('heightin').value;
    var height = heightft*12 + +heightin;
    
    BMI.innerHTML = Math.round((weight /(height*height)) * 703.06957964);
    getDescription(BMI.innerHTML);   }
	
/* Slider function to dynamically display inches portion of the height selected */
 function Slider()
	{heightin_op.innerHTML = document.getElementById('heightin').value;}

/* Interpretation of BMI value */
 function getDescription(thisBMI)

    { var Description = "";
            if (thisBMI<18.5)
                Description ="Underweight - eat a bagel!";
            else if (thisBMI>=18.5 && thisBMI<=24.99)
                Description ="Normal - keep it up!";
            else if (thisBMI>=25 && thisBMI<=29.99)
                Description ="Overweight - exercise more!";
            else if (thisBMI>=30 && thisBMI<=39.99)
                Description ="Obese - get off the couch!";
            else if (thisBMI>=40)
		Description ="Morbidly Obese - take action!";
	  else Description ="Please check your input values, BMI cannot be calculated.";
        
        var DESC = document.getElementById('DESC');
        DESC.innerHTML = Description;
    }
	
  /* Reset Button */
   function Clear()
    {
		document.getElementById('weight').value = "";
		document.getElementById('heightft').value = "";
		document.getElementById('heightin').value = "3";
		document.getElementById('BMI').value = "";
		document.getElementById('DESC').value = "";
		BMI.innerHTML = "";
		DESC.innerHTML = "";
		heightin_op.innerHTML = "3";
    }
</script>

         Java Script is the “brain” of this application. We start with BMICalculate function, which grabs our input variables entered on the form (weight in pounds, height in feet, and height in inches), and performs actual BMI calculation. In order to do that, we first calculate total height in inches, by multiplying feet portion by 12 and adding the result to the inches portion. We also perform some optional, but useful error handling, preventing users from entering invalid values or not specifying these values at all. In case you are wondering, I looked up the weight of the heaviest person ever lived, and the height of the tallest person ever lived to determine maximum possible weight and height parameters. Notice, that we are only validating weight and height (in feet) variables, since height (in inches) is effectively limited by our input control – slider. This should work, as long as you have a newer browser.

         Next function – Slider simply outputs the inches portion of the value selected via slider and makes it available for display on an adjacent label.

         We then use getDescription function to describe BMI value in terms of it being healthy or not. Surprisingly, some of the websites simply calculate BMI value without offering its description.

         The last procedure that we utilize is Clear to reset values of our calculator when clicking on the ‘Reset’ button. This functionality is just a matter of good interface design, that, again is overlooked by most BMI calculators out there. I also preset the inches portion to the value of 3 as explained below.

<form>
<a href="http://blog.excelstrategiesllc.com" target="_blank">
<img src="http://blog.excelstrategiesllc.com/Images/ExcelStrategiesLLC.png" alt ="Excel Strategies, LLC - Logo" height="111" width="320"/>
</a>
<h1>Adult BMI Calculator </h1>

<!-- Setting up form elements for data input-->
<h3>Enter your weight in pounds:</h3>
<input type="number"  id="weight" placeholder = "236">
<b>lbs.</b>
<br>
<h3>Enter you height (in feet and inches):</h3>
<input type="number" id="heightft" placeholder = "6">
<b>ft.</b>

<p class="small"><input type="range" min="0" max="11" value="3" step="1"  id="heightin" style="width:90px;" oninput="Slider()" onchange="Slider()">
<b><label id="heightin_op">3 </label> in.</b></p>


<input type="button" value="Calculate" onClick="BMICalculate()" style="width:90px;"> 
&nbsp;  &nbsp; &nbsp; &nbsp; &nbsp; 
<input type="button" value="Clear" onClick="Clear()" style="width:90px;">

<h2>Your BMI is:</h2>

<!-- Output BMI value and its description -->
<h4><label id="BMI"></label></h4>
<h5><label id="DESC"></label></h5>

</form>

         We’ve already covered CSS and JavaScript portions of our code above, HTML is the substance of the application, providing both: input elements, as well as displaying our results. We start by placing our logo on the calculator, creating a title, then building our form elements and prompts. Notice that input type = “number” will create a textbox with a scroll bar capability on your form. Nify Placeholder will set a default input value that is visible on the form, but not recognized as a valid input until overwritten. I set up my default values for one of the greatest athletes ever lived, and according to the results of this calculation, Mohammed Ali was overweight. This is a clear indication that BMI calculations do not work for world-class athletes, but that shouldn’t concern the rest of us. Since Mohammed Ali was 6’3″, I have also preset slider value to 3 inches, which is in fact recognizable as input, unless changed by us. If changed, our Slider function will execute and display inches value via label adjacent to the slider. Our Calculate command button will fire up our JavaScript code to validate our input and then calculate and display our BMI results. The Clear button simply resets our values. Finally, we have labels that display our results. Overall, form formatting is determined by CSS styles we created in the beginning of our code.

         What should our next JavaScript challenge be? Creating a tip calculator allowing us split the bill with multiple guests?!

         You are more than welcome to to use this calculator on your own website, just copy and paste code below on your webpage:







Leave a Reply

Your email address will not be published. Required fields are marked *