CALCULATOR
html
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Basics</title>
<link href="https://fonts.googleapis.com/css?family=Roboto:400,700&display=swap" rel="stylesheet" />
<link rel="stylesheet" href="css/main.css" />
<script src="js/vendor.js" defer></script>
<script src="js/app.js" defer></script>
</head>
<body>
<header>
<h1>The Calculator</h1>
</header>
<section class="card" id="calculator">
<input type="number" id="input-number" />
<div id="calc-actions">
<button type="button" id="btn-add">+</button>
<button type="button" id="btn-subtract">-</button>
<button type="button" id="btn-multiply">*</button>
<button type="button" id="btn-divide">/</button>
</div>
</section>
<section class="card" id="results">
<h2 id="current-calculation">0</h2>
<h2>Result: <span id="current-result">0</span></h2>
</section>
<section class="card" id="logs">
<ul class="log-entries"></ul>
</section>
</body>
</html>
- vendor.js에서 정의하고 app.js에서 실행하므로 vendor.js를 먼저 씀
app.js
$addBtn.addEventListener('click', (e) => {
calculate(e);
});
$subtractBtn.addEventListener('click', (e) => {
calculate(e);
});
$multiplyBtn.addEventListener('click', (e) => {
calculate(e);
});
$divideBtn.addEventListener('click', (e) => {
calculate(e);
});
vendor.js
const $userInput = document.getElementById('input-number');
const $addBtn = document.getElementById('btn-add');
const $subtractBtn = document.getElementById('btn-subtract');
const $multiplyBtn = document.getElementById('btn-multiply');
const $divideBtn = document.getElementById('btn-divide');
const $currentResult = document.getElementById('current-result');
const $currentCalculation = document.getElementById('current-calculation');
let currentResult = 0;
let currentSign = "";
let count = 1;
const calculate = (e) => {
const target = e.target;
const prevResult = currentResult;
const enteredNumber = +$userInput.value;
if (target.textContent === $addBtn.textContent) {
currentResult += enteredNumber;
currentSign = "+"
} else if (target.textContent === $subtractBtn.textContent){
currentResult -= enteredNumber;
currentSign = "-"
} else if (target.textContent === $multiplyBtn.textContent){
currentResult *= enteredNumber;
currentSign = "*"
} else {
currentResult /= enteredNumber;
currentSign = "/"
}
$currentResult.textContent = currentResult;
const descriptionLog = `${prevResult} ${currentSign} ${enteredNumber}`;
$currentCalculation.textContent = descriptionLog;
const $ul = document.querySelector(".log-entries");
const $newLi = document.createElement('li');
$ul.appendChild($newLi);
$newLi.classList.add('log-entries__item');
$newLi.innerHTML += `${count}. ${$currentCalculation.textContent} = ${$currentResult.textContent}`;
count++;
};