Learn HTML, CSS, and JavaScript by building a calculator

Learning to code can be an exciting and rewarding journey, especially when you start seeing your ideas come to life on the screen. One practical and fun project for beginners is creating a simple calculator using HTML, CSS, and JavaScript. This project will not only teach you the basics of these three core web technologies but also give you a functional tool that you can use and showcase. Let’s dive into this step-by-step guide on how to build your own calculator.

Why Learn Coding by Creating a Calculator?

Practical Application of Skills

Building a calculator encompasses several essential coding skills. You'll learn how to structure your project with HTML, style it with CSS, and add interactivity with JavaScript. These are fundamental skills that will serve as a foundation for any future web development projects.

Understanding the Basics of HTML, CSS, and JavaScript

Creating a calculator helps you grasp the basics of HTML, CSS, and JavaScript in a practical way. HTML forms the structure of the calculator, CSS styles it to look attractive, and JavaScript makes it functional.

Immediate Feedback and Learning

When you create a calculator, you get immediate feedback on whether your code works or not. This is crucial for learning, as you can quickly identify and fix mistakes, helping you understand how coding works in real-time.

Setting Up Your Project

Tools You Need

To get started, you'll need a text editor and a web browser. Popular text editors include Visual Studio Code, Sublime Text, and Atom. You can use any modern web browser like Google Chrome, Firefox, or Edge to test your code.

Creating the Project Structure

Create a new folder for your project. Inside this folder, create three files: index.html, styles.css, and script.js. This structure will help keep your project organized.

Writing the HTML

Basic HTML Structure

Start by setting up the basic HTML structure. Open index.html and write the following code:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Calculator</title>

<link rel="stylesheet" href="styles.css">

</head>

<body>

<div class="calculator">

     <div class="display" id="display"></div>

     <div class="buttons">

         <button class="btn" onclick="appendNumber('1')">1</button>

         <button class="btn" onclick="appendNumber('2')">2</button>

         <button class="btn" onclick="appendNumber('3')">3</button>

         <button class="btn" onclick="appendNumber('+')">+</button>

         <button class="btn" onclick="appendNumber('4')">4</button>

         <button class="btn" onclick="appendNumber('5')">5</button>

         <button class="btn" onclick="appendNumber('6')">6</button>

         <button class="btn" onclick="appendNumber('-')">-</button>

         <button class="btn" onclick="appendNumber('7')">7</button>

         <button class="btn" onclick="appendNumber('8')">8</button>

         <button class="btn" onclick="appendNumber('9')">9</button>

         <button class="btn" onclick="appendNumber('*')">*</button>

         <button class="btn" onclick="appendNumber('0')">0</button>

         <button class="btn" onclick="clearDisplay()">C</button>

         <button class="btn" onclick="calculate()">=</button>

         <button class="btn" onclick="appendNumber('/')">/</button>

     </div>

</div>

<script src="script.js"></script>

</body>

</html>

 

Explanation

  • The <!DOCTYPE html> declaration defines this document as an HTML5 document.
  • The <head> section contains meta information and links to the CSS file.
  • The <body> section contains the main content of the calculator.
  • The div with the class "calculator" houses the display and the buttons.
  • Each button has an onclick event that triggers a function in the JavaScript file.

Styling with CSS

Basic Styling

Open styles.css and add the following CSS to style the calculator:

body {

display: flex;

justify-content: center;

    align-items: center;

height: 100vh;

background-color: #f4f4f4;

margin: 0;

font-family: Arial, sans-serif;

} 

.calculator {

border: 1px solid #ccc;

border-radius: 5px;

padding: 20px;

background-color: #fff;

    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);

}

 

.display {

font-size: 2em;

margin-bottom: 20px;

padding: 10px;

border: 1px solid #ccc;

border-radius: 3px;

background-color: #e0e0e0;

text-align: right;

}

 

.buttons {

display: grid;

    grid-template-columns: repeat(4, 1fr);

gap: 10px;

}

 

.btn {

padding: 20px;

font-size: 1.5em;

border: none;

border-radius: 5px;

cursor: pointer;

background-color: #f0f0f0;

    transition: background-color 0.3s;

} 

.btn:hover {

background-color: #ddd;

} 

.btn:active {

background-color: #ccc;

}

 

Explanation

  • The body style centers the calculator on the screen.
  • The .calculator class styles the main container with padding, border, and shadow.
  • The .display class styles the display area where the calculations appear.
  • The .buttons class creates a grid layout for the buttons.
  • The .btn class styles the buttons, including hover and active states for better user interaction.

Adding Functionality with JavaScript

Basic JavaScript Functions

Open script.js and add the following JavaScript code to make the calculator functional:

let display = document.getElementById('display'); 

function appendNumber(number) {

    display.innerText += number;

} 

function clearDisplay() {

    display.innerText = '';

} 

function calculate() {

try {

        display.innerText = eval(display.innerText);

} catch {

     display.innerText = 'Error';

}

}

 

Explanation

  • The appendNumber function adds the clicked button's value to the display.
  • The clearDisplay function clears the display.
  • The calculate function evaluates the expression in the display using eval(). It includes error handling to catch and display errors.

Enhancing the Calculator

Adding More Features

To make the calculator more advanced, consider adding the following features:

  • Keyboard Support: Allow users to use their keyboard to input numbers and operations.
  • Decimal Point: Add a button for the decimal point to handle floating-point calculations.
  • Backspace Functionality: Allow users to delete the last character entered.

Example of Adding Decimal Point

Update the HTML to include a decimal point button:

<button class="btn" onclick="appendNumber('.')">.</button>

 

Modify the JavaScript to handle multiple decimal points:

function appendNumber(number) {

if (number === '.' && display.innerText.includes('.')) return;

    display.innerText += number;

}

 

Adding Keyboard Support

Add the following JavaScript code to handle keyboard events:

document.addEventListener('keydown', function(event) {

const key = event.key;

if ((key >= 0 && key <= 9) || key === '+' || key === '-' || key === '*' || key === '/') {

        appendNumber(key);

} else if (key === 'Enter') {

        calculate();

} else if (key === 'Backspace') {

     display.innerText = display.innerText.slice(0, -1);

} else if (key === 'Escape') {

        clearDisplay();

}

});

 

Testing and Debugging

Testing Your Calculator

Once you've completed your calculator, thoroughly test it to ensure all functionalities work as expected. Test each button, keyboard input, and edge cases such as division by zero.

Debugging Tips

If your calculator isn't working as expected, use the following tips to debug your code:

  • Check the Console: Open your browser's developer console to check for any error messages.
  • Use Breakpoints: Use breakpoints in your browser's developer tools to pause and inspect the code's execution.
  • Simplify the Problem: If you're stuck, try simplifying the problem by breaking it down into smaller parts.

Conclusion

Building a calculator using HTML, CSS, and JavaScript is an excellent project for beginners to learn coding. It covers the essential skills of structuring a webpage, styling it, and adding interactivity. By following this guide, you should now have a functional calculator and a better understanding of how web development works. Keep experimenting and adding new features to your calculator to further enhance your coding skills.