Welcome folks today in this blog post we will be building a program to calculate area and perimeter of rectangle by length and width
in javascript. All the full source code of the application is given below.
Get Started
In order to get started create a index.html
file and copy paste the code which is shown below
index.html
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 |
<!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> |
Now if you open index.html
file inside the browser you will see the below result