From d9a2c6e338f6c37133ab1094db77a967f7c534e5 Mon Sep 17 00:00:00 2001 From: tamarmatza Date: Sat, 6 Dec 2025 15:56:36 +0200 Subject: [PATCH] feat: calculator excercise tamar m. Write the js for the calc. --- index.html | 80 ++++++++++++++++++++++++++---------------------------- script.js | 77 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 116 insertions(+), 41 deletions(-) create mode 100644 script.js diff --git a/index.html b/index.html index 935c09e..f147b9c 100644 --- a/index.html +++ b/index.html @@ -1,46 +1,44 @@ + + + + Calculator + + - - - - Calculator - - - - -
-
 
-
-
- - - -
-
- - - -
-
- - - -
-
- -
-
- - - + +
+
 
+
+
+ + + +
+
+ + + +
+
+ + + +
+
+ + + + +
+
+ + + +
-
- - - - \ No newline at end of file + + + diff --git a/script.js b/script.js new file mode 100644 index 0000000..237f85e --- /dev/null +++ b/script.js @@ -0,0 +1,77 @@ +/* **************************************************** +* DevClub excercise 2 +* CALCULATOR +/* **************************************************** + * This file implements the logic of a caluclator + * that can do 4 basic operations: (+), (-), (*), (/) +/* **************************************************** */ + +let operand; +let operator; +let result; + +const display = document.querySelector('.display'); +const numbers = document.querySelectorAll('.number'); +const operators = document.querySelectorAll('.row.operations button'); + +numbers.forEach((numButton) => { + numButton.addEventListener('click', () => { + if (display.textContent === '0') { + display.textContent = ''; + } + + operand += numButton.textContent; + + display.textContent += numButton.textContent; + }); +}); + +operators.forEach((button) => { + button.addEventListener('click', () => { + calc(); + + operator = button.textContent; + display.textContent = result + operator; + }); +}); + +clear.addEventListener('click', handleClear); + +equal.addEventListener('click', () => { + calc(); + display.textContent = result; + operand = result; + result = 0; +}); + +handleClear(); + +function calc() { + switch (operator) { + case '+': + result = result + parseInt(operand); + break; + case '-': + result = result - parseInt(operand); + break; + case '*': + result = result * parseInt(operand); + break; + case '/': + result = result / parseInt(operand); + break; + default: + result = parseInt(operand); + } + + operand = ''; + operator = ''; +} + +function handleClear() { + operator = ''; + operand = ''; + result = 0; + + display.textContent = '0'; +}