Simple Calculator Using Html Css Javascript With Source Code

Simple Calculator Using Html Css Javascript With Source Code

6 min read Jun 18, 2024
Simple Calculator Using Html Css Javascript With Source Code

Simple Calculator using HTML, CSS, and JavaScript

This article will guide you through creating a simple calculator using HTML, CSS, and JavaScript. This project is an excellent starting point for beginners to understand how these technologies work together.

HTML Structure

First, let's create the basic HTML structure for our calculator. We will use a div to contain all the elements. Inside this, we'll have a div for the display and another div to hold the buttons.




  Simple Calculator
  


  

CSS Styling

Now, we'll add some basic CSS to style our calculator. In a separate file named style.css, add the following code:

.calculator {
  width: 300px;
  margin: 0 auto;
  border: 1px solid #ccc;
  padding: 10px;
  border-radius: 5px;
}

.display {
  background-color: #eee;
  padding: 10px;
  font-size: 20px;
  text-align: right;
  margin-bottom: 10px;
}

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

.button {
  background-color: #eee;
  padding: 10px;
  border: 1px solid #ccc;
  text-align: center;
  cursor: pointer;
}

JavaScript Logic

Finally, we'll add the JavaScript logic to handle the calculator's functionality. In a separate file named script.js, add the following code:

const display = document.querySelector('.display');
const buttons = document.querySelectorAll('.button');

let currentInput = '';
let previousOperator = null;
let previousOperand = null;

buttons.forEach(button => {
  button.addEventListener('click', () => {
    const value = button.textContent;

    if (value >= '0' && value <= '9') {
      currentInput += value;
    } else if (value === '+' || value === '-' || value === '*' || value === '/') {
      handleOperator(value);
    } else if (value === '=') {
      calculateResult();
    } else if (value === 'C') {
      clearDisplay();
    }

    display.textContent = currentInput;
  });
});

function handleOperator(operator) {
  if (previousOperator) {
    calculateResult();
  }

  previousOperator = operator;
  previousOperand = parseFloat(currentInput);
  currentInput = '';
}

function calculateResult() {
  const currentOperand = parseFloat(currentInput);

  if (previousOperator && previousOperand) {
    switch (previousOperator) {
      case '+':
        currentInput = (previousOperand + currentOperand).toString();
        break;
      case '-':
        currentInput = (previousOperand - currentOperand).toString();
        break;
      case '*':
        currentInput = (previousOperand * currentOperand).toString();
        break;
      case '/':
        if (currentOperand === 0) {
          currentInput = 'Error';
        } else {
          currentInput = (previousOperand / currentOperand).toString();
        }
        break;
    }

    previousOperator = null;
    previousOperand = null;
  }
}

function clearDisplay() {
  currentInput = '';
  previousOperator = null;
  previousOperand = null;
  display.textContent = '';
}

Explanation

  • HTML: We create a basic structure with a display area and a grid of buttons.
  • CSS: We style the calculator with basic colors, borders, and layout using grid properties.
  • JavaScript: We use event listeners to handle button clicks.
  • We handle different button types:
    • Numbers: Append them to currentInput.
    • Operators: Store the operator and the previous operand.
    • Equals: Calculate the result using the stored operator and operands.
    • Clear: Reset all variables and display.

Adding Buttons

Now, you need to add the buttons to the div with the class buttons in your HTML file. You can add them like this:

Running the Calculator

Now, you have a simple calculator working! Save your HTML, CSS, and JavaScript files in the same folder. Open the HTML file in a web browser, and you should see the calculator running.

Remember, this is a basic calculator. You can extend it by adding features like:

  • Advanced operators: Exponents, modulo, etc.
  • Memory functions: Store and recall results.
  • Error handling: Handle division by zero, invalid input, etc.
  • User interface improvements: Add themes, animations, etc.

By exploring the code and trying different modifications, you can gain a deeper understanding of how web development works. Happy coding!