A simple and clean calculator built with vanilla HTML, CSS, and JavaScript.
Users are able to:
- Perform basic arithmetic operations: addition, subtraction, multiplication, and division
- See the result instantly by pressing the
=button - Clear the display with the
Cbutton - See an
Errormessage when an invalid expression is entered
- Solution URL: GitHub
- Live Site URL: GitHub Pages
- Semantic HTML5 markup
- CSS Flexbox (for centering the calculator)
- CSS Grid (for the button layout)
- Vanilla JavaScript (DOM manipulation)
- Inline event handlers (
onclick)
I used grid-template-columns: repeat(4, 1fr) to create a clean 4-column button layout. repeat(4, 1fr) means "4 columns, each taking equal space."
#keys {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 10px;
padding: 25px;
}To center the calculator both horizontally and vertically on the page, I used flexbox on the body with min-height: 100vh so the layout doesn't break on smaller screens.
body {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
}The display input uses readonly so the user cannot type into it directly — they can only interact through the buttons.
<input id="display" readonly />Instead of adding event listeners in JavaScript for each button, I used inline onclick attributes. This way, a single function handles all buttons by receiving different arguments.
<button onclick="appendToDisplay('7')">7</button>
<button onclick="appendToDisplay('+')">+</button>The eval() function is a built-in JavaScript function that evaluates a string as a mathematical expression and returns the result.
display.value = eval(display.value);
// "5+3*2" → 11If the user enters an invalid expression, eval() throws an error. I used try/catch to catch this error and show "Error" on the display instead of crashing the app.
function calculate() {
try {
display.value = eval(display.value);
} catch (error) {
display.value = "Error";
}
}I used hsl() color values for the calculator's dark theme, which makes it easy to adjust lightness for hover and active states.
button {
background-color: hsl(0, 0%, 30%);
}
button:hover {
background-color: hsl(0, 0%, 40%);
}In future projects, I want to focus on:
- TypeScript — adding type safety to JavaScript projects
- Keyboard support — allowing users to type numbers and operators from the keyboard
- Responsive design — making the calculator look good on mobile screens
- Avoiding
eval()— building a custom expression parser for better security
- MDN Web Docs - eval() — Helped me understand how
eval()works and its limitations - MDN Web Docs - CSS Grid — Great reference for building the button grid
- MDN Web Docs - Flexbox — Used for centering the calculator on the page
- GitHub - Ismail-SWE
