How to Make a Simple Calculator in HTML

by Nick Programmer in Circuits > Websites

214 Views, 3 Favorites, 0 Comments

How to Make a Simple Calculator in HTML

CaptureCal.PNG

I created an HTML calculator to provide a simple and user-friendly tool for performing basic arithmetic operations directly within a web browser. This calculator is designed with HTML for structure, CSS for styling, and JavaScript for functionality. The aim is to demonstrate how these web technologies can work together to create an interactive and useful web application.

Supplies

  • Any WEB IDE *recommended

Create an Empty Project

npwindow.PNG
Capturenf.PNG

Step-by-Step Guide


1. Creating a New Project

1. Open WebStorm:

  • Launch WebStorm from your start menu or applications folder

2. Create a New Project:

  • Click on File in the top menu.
  • Select New Project....

3. Select Project Type:

  • In the New Project dialog, choose Empty Project (or simply select Web if you see this option).
  • Set the location for your project by clicking the folder icon and navigating to the desired directory.
  • Click Create to set up your new project.

2. Adding HTML, CSS, and JavaScript Files

1. Open the Project View:

  • In the left-hand pane, ensure you are in the Project view to see your project structure.

2. Add HTML File:

  • Right-click on your project folder (e.g., html_calculator) in the Project view.
  • Select New > HTML File.
  • Name the file index.html and press Enter.

3. Add CSS File:

  • Right-click on your project folder again.
  • Select New > Stylesheet.
  • Name the file styles.css and press Enter.

4. Add JavaScript File:

  • Right-click on your project folder.
  • Select New > JavaScript File.
  • Name the file script.js and press Enter.

HTML Code

Capturecodehtml.PNG

This HTML code creates a simple calculator layout with buttons for numbers, basic arithmetic operators, and actions like clear and delete. Here's a detailed breakdown of what each part does:

1. DOCTYPE and HTML Declaration:

<!DOCTYPE html>
<html lang="en">
  • Declares the document type and the language of the document.

2. Head Section:

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Calculator</title>
<link rel="stylesheet" href="style.css">
</head>
  • Includes metadata about the document, sets the character encoding, viewport settings, title of the page, and links to an external CSS file for styling.

3. Body Section:

<body>
<script src="action.js"></script>
<div>
    <table>
        <tr>
            <label for="display"></label>
            <input type="text" value='' placeholder="0" id="display" class="text_field" readonly>
        </tr>
  • The <script src="action.js"></script> line includes an external JavaScript file for functionality.
  • A <div> contains the entire calculator layout.
  • A <table> element is used to arrange buttons in a grid.
  • The first row contains an input field for displaying the calculator's current value or result.

4. Button Rows:

        <tr>
            <th><button onclick="appendToDisplay('7')">7</button></th>
            <th><button onclick="appendToDisplay('8')">8</button></th>
            <th><button onclick="appendToDisplay('9')">9</button></th>
            <th><button onclick="appendToDisplay('/')" class="operator">/</button></th>
        </tr>
        <tr>
            <th><button onclick="appendToDisplay('4')">4</button></th>
            <th><button onclick="appendToDisplay('5')">5</button></th>
            <th><button onclick="appendToDisplay('6')">6</button></th>
            <th><button onclick="appendToDisplay('*')" class="operator">*</button></th>
        </tr>
        <tr>
            <th><button onclick="appendToDisplay('1')">1</button></th>
            <th><button onclick="appendToDisplay('2')">2</button></th>
            <th><button onclick="appendToDisplay('3')">3</button></th>
            <th><button onclick="appendToDisplay('-')" class="operator">-</button></th>
        </tr>
        <tr>
            <th><button onclick="appendToDisplay('.')">.</button></th>
            <th><button onclick="appendToDisplay('0')">0</button></th>
            <th><button onclick="clear_all()" class="operator">C</button></th>
            <th><button onclick="erase()" class="operator">⌫</button></th>
        </tr>
    </table>
    <button onclick="equals()" class="equals">=</button>
</div>
</body>
  • Each <tr> represents a row in the calculator.
  • <th> elements contain buttons with onclick attributes calling various JavaScript functions to handle button clicks.
  • appendToDisplay() is a JavaScript function that appends value to the display.
  • The last button outside the table is the equals (=) button, which performs the calculation.

CSS Code

Capturecodehtml.PNG

This CSS code styles various elements of a calculator interface, focusing on buttons, the text field, and the equals button. Here’s a detailed breakdown of each section:

General Button Styling

button {
    width: 70px;
    height: 60px;
    border-radius: 12px;
    border-width: 2px;
    font-size: 200%;
}
  • Width and Height: Sets the dimensions of the buttons to 70 pixels wide and 60 pixels high.
  • Border Radius: Makes the corners of the buttons rounded with a 12-pixel radius.
  • Border Width: Sets the border width to 2 pixels.
  • Font Size: Increases the font size to 200% of the default size, making the button text large and easy to read.

Operator Button Styling

.operator {
background: orange;
}
  • Background Color: Sets the background color of buttons with the operator class to orange, distinguishing them from other buttons.

Text Field Styling

.text_field {
    width: 280px;
    height: 60px;
    font-size: 200%;
    border-radius: 10px;
    margin-left: 4px;
}
  • Width and Height: Sets the dimensions of the text field to 280 pixels wide and 60 pixels high.
  • Font Size: Increases the font size to 200% of the default size, ensuring the displayed text is large and readable.
  • Border Radius: Adds rounded corners to the text field with a 10-pixel radius.
  • Margin Left: Adds a left margin of 4 pixels, providing some space from adjacent elements.

Equals Button Styling

.equals {
background: orange;
width: 292px;
height: 60px;
border-radius: 10px;
border-width: 2px;
margin-left: 3px;
}
  • Background Color: Sets the background color to orange, consistent with the operator buttons.
  • Width and Height: Sets the dimensions to 292 pixels wide and 60 pixels high, likely to make it visually distinct and larger than other buttons.
  • Border Radius: Adds rounded corners with a 10-pixel radius.
  • Border Width: Sets the border width to 2 pixels.
  • Margin Left: Adds a left margin of 3 pixels, spacing it slightly from adjacent elements.

Hover Effect for Buttons

button:hover {
    border-radius: 12px;
    border-width: 3px;
    border-color: gray;
}
  • Border Radius: Ensures the border radius remains 12 pixels when hovered.
  • Border Width: Increases the border width to 3 pixels on hover, providing a visual cue that the button is interactive.
  • Border Color: Changes the border color to gray on hover, further emphasizing the hover state.

Summary

This CSS code enhances the user interface of the calculator by ensuring that:

  • Buttons are consistently sized and easily readable with large text.
  • Operator buttons and the equals button have a distinct orange background for easy identification.
  • The text field is prominently styled to display input and results clearly.
  • Buttons have a responsive hover effect to improve user interaction feedback.

JavaScript Code

Capturecodehtml.PNG

This code defines a set of JavaScript functions for implementing a basic calculator functionality in a web page. Let's break down each function:

appendToDisplay(input)

function appendToDisplay(input){
if(document.getElementById("display") != null){
document.getElementById("display").value += input;
}else{
console.error("Element not found");
}
}

This function takes an input character or string and appends it to the value of an element with the ID "display". It first checks if the element exists in the DOM. If it does, it appends the input to the value of the element. If not, it logs an error to the console.

clear_all()

function clear_all(){
document.getElementById("display").value = "";
}

This function clears the value of the element with the ID "display" by setting its value to an empty string.

equals()

function equals(){
try {
document.getElementById("display").value = eval(document.getElementById("display").value);
}catch(error){
document.getElementById("display").value = 'Error';
}
}

This function evaluates the expression present in the value of the element with the ID "display" using JavaScript's eval() function. If the evaluation is successful, it updates the value of the element with the result. If an error occurs during evaluation, it sets the value of the element to 'Error'.

erase()

function erase(){
document.getElementById("display").value = document.getElementById("display").value.replace(/.$/, '');
}

This function removes the last character from the value of the element with the ID "display", effectively acting as a backspace function.

Overall, these functions work together to provide basic calculator functionality such as inputting numbers and operators, clearing the display, evaluating expressions, and erasing characters.

The Full Code

Capturefit.PNG

You can find the final version of each file on my GitHub - https://github.com/NickProgrammerOffical/A-Simple-Calculator-in-HTML

Just click on Code > Download ZIP


*Interesting fact: This instructable was 80% written by ChatGPT-4