Perimeter: The perimeter is the length of the outline of a shape. To find the perimeter of a rectangle or square you have to add the lengths of all the four sides. x is in this case the length of the rectangle while y is the width of the rectangle.
Area: The area is measurement of the surface of a shape. To find the area of a rectangle or a square you need to multiply the length and the width of a rectangle or a square.
Result:
JavaScript Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | <!doctype html> <html> <head> <title>Code4Examples</title> <meta charset="utf-8"> <style> label{ display: block; } </style> </head> <body> <h1>Area and Perimeter of Rectangle</h1> <h2 id="area"></h2> <h2 id="perimeter"></h2> <label for="len">Length: <input type="text" id="len"> </label> <label for="wid">Width: <input type="text" id="wid"> </label> <button id="calcBtn">Calculate</button> <script> //get inputs and button element from document var lenEl=document.querySelector("#len"); var widEl=document.querySelector("#wid"); var calcBtn=document.querySelector("#calcBtn"); var areagEl=document.querySelector("#area"); var perimeterEl=document.querySelector("#perimeter"); //bind a function tothe onClick event the AddBtn calcBtn.onclick=function(){ //area formule length*width area=Number(lenEl.value)*Number(widEl.value) //perimeter formule 2*(length+width) perimeter=2*(Number(lenEl.value)+Number(widEl.value)) //write the results into #area #perimeter document areagEl.innerHTML="Area of rectange:"+area; perimeterEl.innerHTML="Perimeter of rectange:"+perimeter; } </script> </body> </html> |
[…] Calculate Area and Perimeter of Rectangle in JavaScript […]