JSFiddle - React, Tailwind, and code Playground

by dvjc

HTML

<!-- Goal - Implement Huron's Formula for area of a triangle -->
<div>
    <div id="divA">
        <label id="lbA">Side A Length:</label>
        <input type="text" id="txA" value="7" class="sides" />
    </div>
    <div id="divB">
        <label id="lbB">Side B Length:</label>
        <input type="text" id="txB" value="4" class="sides" />
    </div>
    <div id="divC">
        <label id="lbC">Side C Length:</label>
        <input type="text" id="txC" value="5" class="sides" />
    </div>
    <div id="divArea">
        <input type="button" id="btnCalculate" value="Calculate Area" onclick="calculateArea();" />
    </div>
    <div id="divResult">
        <label id="lbResult">Area:</label>
        <input type="text" id="txtResult" class="result" />
    </div>
</div>

CSS

.sides {
    width: 20px;
}
.result {
    width: 40px;
}

JavaScript

function calculateArea() {
    // grabs the lengths of each side
    // this also does type-coercion to number
    var a = 1 * document.getElementById("txA").value;
    var b = 1 * document.getElementById("txB").value;
    var c = 1 * document.getElementById("txC").value;

    // use Huron formula for area
    var Area = getHuronArea( a, b, c );
    
    // spits out result
    document.getElementById("txtResult").value = Area;
}

// Area = root of (s(s-a)(s-b)(s-c))
// and s = (a+b+c)/2
function getHuronArea(a, b, c){
    // required by Huron formula - the semi-perimeter
    var s = (a + b + c) / 2;

    // next portion of Huron formula
    var preArea = (s * (s-a) * (s-b) * (s-c));
    
    // applies a squre root to the preArea
    // this also rounds to 3 decimal places
    var Area = Math.round(Math.sqrt(preArea)*1000)/1000;
   
    // returns the area
    return Area;    
}