📌계산기 display의 첫 번째,두번째 칸에 숫자 나타내기
📌출력된 숫자와 연산자로 계산하기
📌ac버튼을 누르면 화면을 초기화시키기
를 기본적인 기능으로 구현하고, userflow를 위한 코드는 밑에 추가했다.
const calculator = document.querySelector('.calculator');
const buttons = calculator.querySelector('.calculator__buttons');
const firstOperend = document.querySelector('.calculator__operend--left');
const operator = document.querySelector('.calculator__operator');
const secondOperend = document.querySelector('.calculator__operend--right');
const calculatedResult = document.querySelector('.calculator__result');
buttons.addEventListener('click', function (event) {
const target = event.target;
const action = target.classList[0];
const buttonContent = target.textContent;
if (target.matches('button')) {
if (action === 'number') {
console.log('숫자 ' + buttonContent + ' 버튼');
if (firstOperend.textContent === '0'){
firstOperend.textContent = buttonContent;
} else {
secondOperend.textContent = buttonContent;
}
}
if (action === 'operator') {
operator.textContent = buttonContent;
console.log('연산자 ' + buttonContent + ' 버튼');
}
if (action === 'clear') {
console.log('초기화 버튼');
firstOperend.textContent = '0';
secondOperend.textContent = '0';
calculatedResult.textContent = '0'
}
if (action === 'calculate') {
console.log('계산 버튼');
calculatedResult.textContent = calculate(firstOperend.textContent, operator.textContent, secondOperend.textContent);
}
}
});
+userflow 기능추가
📖숫자버튼을 누를때 숫자 연속적으로 나오게하기
📖연산자 버튼 동작시키기
📖enter,ac버튼 동작
const display = document.querySelector('.calculator__display--for-advanced');
let firstNum, operatorForAdvanced, previousKey, previousNum;
buttons.addEventListener('click', function (event) {
const target = event.target;
const action = target.classList[0];
const buttonContent = target.textContent;
if (target.matches('button')) {
if (action === 'number') {
if(previousKey === 'operator' || display.textContent === '0'){
display.textContent = buttonContent;
previousKey = action;
} else {
display.textContent += buttonContent;
}
previousNum = display.textContent;
}
if (action === 'operator') {
operatorForAdvanced = buttonContent;
previousKey = action;
firstNum = display.textContent;
}
if(display.textContent === '0'){
display.textContent += buttonContent;
} else {
display.textContent = previousNum + buttonContent;
}
}
if (action === 'clear') {
firstNum = '0';
operatorForAdvanced = '';
display.textContent = '0';
previousNum = '0';
previousKey = action;
}
if (action === 'calculate') {
if(operatorForAdvanced !== '')
{
if (firstNum === previousNum){
display.textContent = calculate(display.textContent, operatorForAdvanced, previousNum)
}
else{
display.textContent = calculate(firstNum, operatorForAdvanced, previousNum)
}
}
console.log(firstNum, previousNum, display.textContent);
}
}
});