Welcome back to the second part of our tutorial on building a simple calculator application! In this installment, we'll dive deeper into the functionality of our calculator and cover tasks 5 through 17. If you missed the first part, make sure to check it out here.
Task 5: Handling Operator Inputs
To handle operator inputs, we need to keep track of the current input and the operator chosen by the user. Update the event listener for operator buttons in your script.js
file:
// Inside the button event listener for operators
} else if (button.classList.contains('operator')) {
if (currentInput !== '') {
currentInput += ` ${button.textContent} `;
display.textContent = currentInput;
}
}
Task 6: Implementing Decimal Point
Allow users to input decimal points in their calculations. Update the event listener for number buttons:
// Inside the button event listener for number buttons
} else if (button.classList.contains('number')) {
currentInput += button.textContent;
display.textContent = currentInput;
}
Task 7: Handling Calculation
When the user clicks the equals button, calculate the result and display it on the screen:
// Inside the button event listener for equals button
} else if (button.classList.contains('equals')) {
try {
currentInput = eval(currentInput).toString();
display.textContent = currentInput;
} catch (error) {
display.textContent = 'Error';
}
}
Task 8: Implementing Clear Functionality
Allow users to clear the current input or reset the calculator:
// Inside the button event listener for clear button
} else if (button.classList.contains('clear')) {
currentInput = '';
display.textContent = '0';
}
Task 9: Keyboard Support
Add support for keyboard input to enhance user experience:
document.addEventListener('keydown', event => {
const key = event.key;
const allowedKeys = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '-', '*', '/', '.', '=', 'Enter', 'Backspace', 'Escape'];
if (allowedKeys.includes(key)) {
event.preventDefault();
const button = document.querySelector(`.button:contains('${key}')`);
if (button) button.click();
}
});
Task 10: Styling Enhancements
Update the CSS to improve the visual appearance of the calculator:
/* Add styling to the buttons */
.button {
width: 50px;
height: 50px;
font-size: 18px;
border: none;
background-color: #e0e0e0;
margin: 5px;
cursor: pointer;
}
Stay tuned for the next part of our tutorial, where we'll wrap up the development of our simple calculator app by adding more features and improving user interactions.