EN ES
Home > Web development > Javascript Tutorials > How to Create a Basic Calculator with HTML, CSS, and JavaScript

How to Create a Basic Calculator with HTML, CSS, and JavaScript

Diego Cortés
Diego Cortés
September 28, 2024
How to Create a Basic Calculator with HTML, CSS, and JavaScript

Creating a basic calculator is an excellent project for beginners who want to learn web programming using HTML, CSS, and JavaScript. This article will guide you step by step in building your own calculator from scratch.

File Structure

To get started, create a folder on your computer for your project. Inside this folder, you can create three files:

  • index.html
  • styles.css
  • script.js

Creating the HTML File

The first step is to define the basic structure of your calculator in HTML. Open index.html and add the following content:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Basic Calculator</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="calculator">
        <input type="text" id="display" disabled>
        <div class="buttons">
            <button class="btn" onclick="clearDisplay()">C</button>
            <button class="btn" onclick="appendToDisplay('7')">7</button>
            <button class="btn" onclick="appendToDisplay('8')">8</button>
            <button class="btn" onclick="appendToDisplay('9')">9</button>
            <button class="btn" onclick="appendToDisplay('/')">/</button>
            <button class="btn" onclick="appendToDisplay('4')">4</button>
            <button class="btn" onclick="appendToDisplay('5')">5</button>
            <button class="btn" onclick="appendToDisplay('6')">6</button>
            <button class="btn" onclick="appendToDisplay('*')">*</button>
            <button class="btn" onclick="appendToDisplay('1')">1</button>
            <button class="btn" onclick="appendToDisplay('2')">2</button>
            <button class="btn" onclick="appendToDisplay('3')">3</button>
            <button class="btn" onclick="appendToDisplay('-')">-</button>
            <button class="btn" onclick="appendToDisplay('0')">0</button>
            <button class="btn" onclick="appendToDisplay('+')">+</button>
            <button class="btn" onclick="calculateResult()">=</button>
        </div>
    </div>
    <script src="script.js"></script>
</body>
</html>

Explanation of the HTML File

  • The <input> element is used to display the results of the calculator.
  • The buttons allow users to interact with the calculator.
  • The functions invoked when clicking the buttons are defined in the JavaScript file script.js.

CSS Styles for the Calculator

Next, we will style the calculator. Open styles.css and add the following CSS:

body {
    font-family: Arial, sans-serif;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background-color: #f4f4f4;
}

.calculator {
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    padding: 20px;
    min-width: 200px;
}

input[type="text"] {
    width: 100%;
    height: 40px;
    margin-bottom: 10px;
    text-align: right;
    font-size: 18px;
    border: 1px solid #ccc;
    border-radius: 5px;
    padding: 5px;
}

.buttons {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 10px;
}

.btn {
    padding: 20px;
    font-size: 18px;
    background-color: #007BFF;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
}

.btn:hover {
    background-color: #0056b3;
}

Explanation of the CSS Styles

  • Flexbox is used to center the calculator on the page.
  • The .calculator container has a white background, rounded corners, and a shadow to give it a modern look.
  • The buttons have a simple yet appealing design with a color that changes when hovered over.

JavaScript Logic

Finally, we will implement the logic behind the calculator. Open script.js and add the following code:

function appendToDisplay(value) {
    const display = document.getElementById('display');
    display.value += value;
}

function clearDisplay() {
    const display = document.getElementById('display');
    display.value = '';
}

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

Explanation of the JavaScript Code

  • appendToDisplay(value): Adds the value of a button to the input field.
  • clearDisplay(): Clears the calculator's display.
  • calculateResult(): Evaluates the mathematical expression entered and shows the result. It uses eval(), which is useful for this simple example. However, in larger projects, it is recommended to avoid its use for security reasons.

Testing the Calculator

Now that we have created the calculator, open index.html in your browser and test its functionality. You should be able to perform basic mathematical operations like addition, subtraction, multiplication, and division.

Tips for Improving the Calculator

  1. Input Validation: Add validation to ensure that users do not enter invalid characters.
  2. Enhance the Interface: Consider adding transitions and animations to improve the user experience.
  3. Advanced Functions: Add functionalities like square root, exponents, or memory.

Conclusion

Creating a basic calculator with HTML, CSS, and JavaScript is a valuable exercise for developing your web programming skills. Throughout this article, we covered the creation of the HTML structure, styling with CSS, and functionality with JavaScript. With this knowledge, you can expand and improve your calculator or apply the skills you've gained to other projects.

If you enjoyed this article, don't forget to share it with your friends and keep learning about web development. Good luck on your journey to becoming a web programmer!

Diego Cortés
Diego Cortés
Full Stack Developer, SEO Specialist with Expertise in Laravel & Vue.js and 3D Generalist

Categories

Page loaded in 27.96 ms