Simple Calculator Code In Html And Javascript With Source Code

Simple Calculator Code In Html And Javascript With Source Code

5 min read Jun 18, 2024
Simple Calculator Code In Html And Javascript With Source Code

Simple Calculator Code in HTML and JavaScript

This article will guide you through creating a simple calculator using HTML and JavaScript. The calculator will perform basic arithmetic operations like addition, subtraction, multiplication, and division.

HTML Structure

First, we'll set up the basic HTML structure for our calculator.




    
    
    Simple Calculator
    


    

This HTML code creates a basic layout for our calculator:

  • A display input field (read-only) to show the numbers and operations.
  • A buttons container holding the numerical buttons (0-9, .), operator buttons (+, -, *, /), an equals button (=), and a clear button (C).

JavaScript Functionality

Now, let's add JavaScript code to handle the calculator's logic:

let display = document.getElementById("display");
let currentInput = "";

function appendNumber(num) {
  currentInput += num;
  display.value = currentInput;
}

function appendOperator(operator) {
  currentInput += operator;
  display.value = currentInput;
}

function calculate() {
  try {
    display.value = eval(currentInput);
    currentInput = display.value;
  } catch (error) {
    display.value = "Error";
  }
}

function clearDisplay() {
  currentInput = "";
  display.value = "";
}

This JavaScript code does the following:

  1. Selects elements: It gets references to the display element and stores it in a variable.
  2. appendNumber(num): This function appends the clicked number to the currentInput and updates the display.
  3. appendOperator(operator): This function appends the clicked operator to the currentInput and updates the display.
  4. calculate(): This function evaluates the currentInput using eval() and displays the result. It also handles potential errors during evaluation.
  5. clearDisplay(): This function clears the currentInput and the display.

Putting It All Together

Now you have a simple calculator with basic functionality! Feel free to add more features like parentheses, history, or advanced operations.

Remember to add your own CSS styling to make the calculator visually appealing.

This is a basic example. You can expand upon this by adding more features like:

  • Memory functions: Store and retrieve previous results.
  • Advanced operations: Implement functions like square root, percentage, etc.
  • Error handling: Provide user-friendly error messages for invalid inputs.
  • Styling: Use CSS to create a visually appealing and intuitive user interface.

This simple calculator code provides a foundation for building more complex and user-friendly calculators.

Featured Posts