-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
131 lines (81 loc) · 2.56 KB
/
script.js
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
const add = (a, b) => {return a + b};
// Function for subtracting
const subtract = (a, b) => {return a - b};
// Function for multiplying
const multiply = (a, b) => {return a * b};
// Function for dividing
const divide = (a, b) => {return a / b};
// Binding for display value
let displayValue = "";
// Binding for operator value
let operatorValue = null;
let numInput = "";
// Binding for firstNum
let firstNum = "";
// Binding for secondNum
let secondNum = "";
// Binding for DOM selection .number
let buttons = document.querySelectorAll(".number");
// Create a node list
buttons.forEach((button) => {
// Click event listener wich calls screen function
button.addEventListener('click', screen);
});
// Function to display numbers pressed on display
function screen(e) {
displayValue += e.target.textContent;
document.getElementById("display").textContent = displayValue;
}
// Binding for DOM selection .operator
let pressOperator = document.querySelectorAll(".operator")
// Create a node list
pressOperator.forEach((button) => {
// Click event listener wich calls storeInput function
button.addEventListener('click', storeInput);
});
// Funtion for storing first number value
function storeInput(e) {
if(operatorValue !== null) check();
firstNum = parseInt(displayValue);
operatorValue = e.target.textContent;
// Clear display
displayValue = "";
// Display firstNum and operatorValue
document.getElementById("display").textContent = `${firstNum} ${operatorValue}`;
}
function check() {
secondNum = parseInt(displayValue);
document.getElementById("display").textContent = operate(operatorValue, firstNum,secondNum);
displayValue = document.getElementById("display").textContent;
}
// Code for equating expression
let equate = document.querySelector(".equals");
equate.addEventListener('click', answer);
function answer(e) {
check();
}
const operate = function (operator, a, b) {
switch(operator) {
case "+":
return add(a,b);
break;
case "-":
return subtract(a,b);
break;
case "x":
return multiply(a, b);
break;
case "/":
return divide(a,b);
}
}
// Clear display & input bindings
let clear = document.getElementById("clear");
clear.addEventListener('click', clearScreen);
function clearScreen(e) {
displayValue = "";
operatorValue= "";
firstNum = "";
secondNum = "";
document.getElementById("display").textContent = displayValue;
}