/
script.js
119 lines (103 loc) · 2.83 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
$(function(){ //document ready
var output, temp, evaluated, error
output = temp = ""
evaluated = error = false
var $outputScreen = $("#outputScreen")
var $resultScreen = $("#resultScreen")
function clickedSign() {
$button = $(this)
$button.addClass("clicked")
setTimeout(function(){$button.removeClass("clicked");}, 100);
}
function clear() { output = temp = "" }
function addBracket(){
var open = temp.lastIndexOf("(")
var close = temp.lastIndexOf(")")
var chosenBracket
if(open>close){
chosenBracket = ")"
}else if(close>open){
chosenBracket = "("
}else if(open===close){ //else if no bracket exists yet
chosenBracket = "("
};
output = output + chosenBracket;
temp = temp + chosenBracket;
};
// special callbacks to execute right after evaluated
$(".buttons").on( "click", function(){
if (error){
$resultScreen.text( "" )
error = false
};
})
$(".numbers, #dot, #bracket").on( "click", function(){
if (evaluated){
clear()
$resultScreen.text( "" )
evaluated = false
}
})
$(".basic-operators").on( "click", function(){
if (evaluated){
output = temp = $resultScreen.text()
$resultScreen.text( "" )
evaluated = false
}
})
$("#backspace").on( "click", function(){
if (evaluated){
$resultScreen.text( "" )
evaluated = false
}
})
// main callbacks to execute when a button is pressed
$(".numbers, #dot").on( "click", function(){
output = output + ($(this).text());
temp = temp + ($(this).text());
});
$("#add").on( "click", function(){
output = output + ($(this).text());
temp = temp + "+";
});
$("#substract").on( "click", function(){
output = output + ($(this).text());
temp = temp + "-";
});
$("#divide").on( "click", function(){
output = output + ($(this).text());
temp = temp + "/";
});
$("#multiply").on( "click", function(){
output = output + ($(this).text());
temp = temp + "*";
});
$("#bracket").on( "click", addBracket );
$("#clear").on( "click", clear );
$("#backspace").on( "click", function(){
output = output.slice(0,-1)
temp = temp.slice(0,-1)
});
$("#option").on( "click", function() {
alert("This option button can be used to switch the calculator layout to scientific calculator")
});
$("#equal").on( "click", function() {
try {
$resultScreen.text( eval(temp) )
evaluated = true
}
catch(err) {
if (err instanceof SyntaxError || TypeError) {
$resultScreen.text( "Syntax Error" )
error = true
}
}
});
$(".buttons")
.on( "click", clickedSign )
.on( "click", function(){
$outputScreen.text(output)
//alert to debug temp
//alert(temp)
})
});