Calculator made in HTML, CSS, and JS. Project for The Odin Project
HTML
For HTML, I'm going to use Flexbox to create a grid that contains a display
, number buttons (0-9), 5 operator
buttons (+, -, *, /, and =).
CSS
JavaScript
-
Functions for:
- Addition
- Subtraction
- Multiplication
- Division
-
A function
operate()
that takes anoperator
and 2 numbers and calls one of the above functions on the numbers -
A function that populates the display after clicking on a number button
Step-by-Step
-
Create boilerplate HTML
-
Connect CSS and JS scripts to HTML
-
HTML
- Create a container to house and align the entire webpage
- Within that container, create another container to manage the items inside the calculator (buttons, display, etc)
- Add the following inside the calculator container:
- A div for displaying the selected
number
,operator
, and finally theresults
- 10 buttons for the numbers 0-9
- 5 buttons for the
operators
, +, -, *, /, and = - A button for decimal
- A div for displaying the selected
-
CSS
- Apply resets to all elements in the page
- Set container width and height to 100% of the viewport and hide overflow for neatness
- Apply
display: flex
to the container and setflex-direction
tocolumn
-
JavaScript
- Add event listeners for each button needed
- Create global variables for
currentNum
,operatingNum
,operator
, andresult
- Each number button must store its respective number in variable. When the user clicks a number for the first time and hasn't yet clicked an operator, that number is stored in
currentNum
, else it becomes theoperatingNum
- Create global variables for
- Create functions for each basic operation
add()
takescurrentNum
and addsoperatingNum
to itsubtract()
takescurrentNum
and subtractsoperatingNum
from itmultiply()
takescurrentNum
and multiplies it byoperatingNum
divide()
takescurrentNum
and divides it byoperatingNum
- Create a function
operate()
that takes in a stringoperator
and two numbersoperate()
will call one of the operation functions based on the stringoperator
and pass them the two numbers provided.operate()
will be called as a result of pressing the = button IFcurrentNum
,operatingNum
, andoperator
are valid and filled
- Create a
updateDisplay()
function that is called every time a button is pressed.updateDisplay()
will takecurrentNum
,operatingNum
, and theoperator
and add them on the display as a string for easy viewing
- Add event listeners for each button needed
Pseudocode