How to make a Calculator with Html Css JS | Simple Calculator

Building a Simple Calculator Web App with HTML, CSS, and JavaScript

Have you ever wanted to create your own calculator on the web? Maybe you’re learning web development and want a fun project to practice your skills. Well, you’re in luck! In this tutorial, we’ll walk through building a simple calculator using HTML, CSS, and JavaScript. Don’t worry if you’re new to coding – we’ll explain everything step by step.

HTML: Setting Up the Structure

Let’s start with the HTML code. HTML provides the structure of our calculator. We’ll use <div> elements to organize different parts of the calculator – the display, buttons, and labels.





<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Simple Calculator</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="main-calculator">
        <div class="output-black">
            <input class="output-text" type="text" id="display" placeholder="0" readonly>
        </div>
        <div class="serpent-label">
            <div class="left-side">
                <button>Mute Sound</button>
                <button>Countdown</button>
            </div>
            <div class="right-side">Serpent Coding</div>
        </div>
        <div class="buttons-of-cal">
            <div class="first-two-rows">
                <button onclick="appendNumber('7')">7</button>
                <button onclick="appendNumber('8')">8</button>
                <button onclick="appendNumber('9')">9</button>
                <button onclick="appendOperator('/')">/</button>
                <button onclick="appendOperator('*')">*</button>
                <button onclick="appendNumber('4')">4</button>
                <button onclick="appendNumber('5')">5</button>
                <button onclick="appendNumber('6')">6</button>
                <button onclick="appendNumber('0')">0</button>
                <button onclick="appendOperator('-')">-</button>
            </div>
            <div class="bottom-rows">
                <div class="right-side-zero">
                    <div class="right-side-upper">
                        <button onclick="appendNumber('1')">1</button>
                        <button onclick="appendNumber('2')">2</button>
                        <button onclick="appendNumber('3')">3</button>
                        <button onclick="appendNumber('00')">00</button>
                    </div>
                    <div class="right-side-bottom"> 
                        <button onclick="clearDisplay()">AC</button>
                        <button onclick="appendNumber('.')">.</button>
                        <button onclick="calculate()">=</button>
                    </div>
                </div>
                <div class="left-side-plus">
                    <button onclick="appendOperator('+')">+</button>
                </div>
            </div>
        </div>
    </div>
    <script src="script.js"></script>
</body>
</html>

Explanation:

  • <!DOCTYPE html>: This declaration specifies the document type and version of HTML.
  • <html lang="en">: The opening tag for the HTML document, specifying the language as English.
  • <head>: Contains meta-information about the HTML document, such as character encoding, viewport settings, and the title.
  • <meta charset="UTF-8">: Specifies the character encoding for the document as UTF-8, which supports a wide range of characters.
  • <meta name="viewport" content="width=device-width, initial-scale=1.0">: Sets the viewport width to the device width and initial zoom level to 1.0, ensuring proper scaling on different devices.
  • <title>Simple Calculator</title>: Sets the title of the web page.
  • <link rel="stylesheet" href="styles.css">: Links an external CSS file named “styles.css” to style the HTML elements.
  • <body>: Contains the content of the web page.
  • <div class="main-calculator">: Represents the main container for the calculator.
  • <div class="output-black">: Contains the display area for showing numbers and results.
  • <input class="output-text" type="text" id="display" placeholder="0" readonly>: An input field with the class “output-text” and ID “display” to display numbers and results. It has a placeholder of “0” and is set to readonly to prevent user input.
  • <div class="serpent-label">: Contains labels for additional functionalities.
  • <div class="left-side"> and <div class="right-side">: Display buttons for muting sound, countdown, and “Serpent Coding”.
  • <div class="buttons-of-cal">: Contains the buttons for numbers and operators.
  • <div class="first-two-rows"> and <div class="bottom-rows">: Organizes the buttons into rows.
  • <script src="script.js"></script>: Links an external JavaScript file named “script.js” to add functionality to the calculator.
  • This HTML structure sets up the foundation for the calculator, organizing elements into appropriate sections.
@import url('https://fonts.googleapis.com/css2?family=Orbitron:wght@400..900&display=swap');
body{
    background-color: rgb(247, 247, 247);
    display: flex;
    align-items: center;
    justify-content: center;
    font-family: 'Orbitron';
}

*{
font-family: 'Orbitron';
}


.main-calculator{
position: relative;
width: 407px; 
height: 415px;
padding: 10px;
box-shadow: 0px 0px 7.6px 2.4px rgba(0, 0, 0, 0.18),inset 0px 0px 21px 0px rgba(194, 194, 194, 0.004);
 
}


.output-black{
box-sizing: border-box;
width: 100%;
height: 67px;
background: #000000;
border: 1px solid #DDDDDD;
box-shadow: inset 0px 4px 4px rgba(0, 0, 0, 0.25);
border-radius: 5px;
}
.output-text{
    width: 100%; 
    font-family: 2em/1 "VT323", monospace;
    background-color: transparent;
    border: none;
    height: 100%;
    color: white;
font-style: normal;
font-weight: 400;
font-size: 36px;
line-height: 45px;
color: White;
backdrop-filter: blur(2px);
}

.serpent-label{
    width: 100%;
    display: flex;
font-weight: 600;
font-size: 12px;
color: #411414;
margin-top: 4px;

}
.serpent-label  div:nth-child(1){
    width: 50%;
display: flex;
gap:2px;
}
.serpent-label  div:nth-child(1) button{
font-weight: 600;
font-size: 12px;
width: auto;
background: #FFFFFF;
border: 1px solid #F6F6F6;
box-shadow: 3px 5px 5.5px rgba(0, 0, 0, 0.09);
border-radius: 7px;

}



.serpent-label  div:nth-child(2){
    width: 50%;
display: flex;
align-items: center;
justify-content: end;
gap:2px;
}

.buttons-of-cal, {
    display: flex;
}

.first-two-rows{
    padding-top: 10px;
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    gap: 10px;
    justify-content: center;
    
    
}

.first-two-rows button{
width: 18%;
height: 71px;
background: #FFFFFF;
border: 1px solid #F6F6F6;
box-shadow: 3px 5px 5.5px rgba(0, 0, 0, 0.09);
border-radius: 7px;

}

.bottom-rows{
    display: flex;
    flex-direction: row;
    gap: 3px;
    padding-top: 10px;
}
.left-side-plus{
    width: 20%;
}

.right-side-zero{
    display: flex;
    width: 80%;
    flex-direction: column;
   
}

.right-side-upper{
    
    display: flex;
    gap:10px;
}
.right-side-bottom{
    
    display: flex;
    gap:10px;
    padding-top: 10px;
}

.right-side-upper button{
width: 25%;
height: 71px;
background: #FFFFFF;
border: 1px solid #F6F6F6;
box-shadow: 3px 5px 5.5px rgba(0, 0, 0, 0.09);
border-radius: 7px;
}
.right-side-bottom button{
width: 25%;
height: 71px;
background: #FFFFFF;
border: 1px solid #F6F6F6;
box-shadow: 3px 5px 5.5px rgba(0, 0, 0, 0.09);
border-radius: 7px;
}
.right-side-bottom button:nth-child(3){
width: 50%;
}
.left-side-plus button{
    width: 100%;
    height: 100%;
background: black;
color: white;
font-size: 40px;
border: 1px solid #F6F6F6;
box-shadow: 3px 5px 5.5px rgba(0, 0, 0, 0.09);
border-radius: 7px;
}

button:hover{
    color: white;;
    background-color: black;
    transition: 0.7s ease;
}

Explanation:

  • @import url('https://fonts.googleapis.com/css2?family=Orbitron:wght@400..900&display=swap');: Imports the Orbitron font from Google Fonts to use in the calculator.
  • body: Applies styles to the body element.
  • background-color: Sets the background color of the body to a light gray.
  • display: flex;: Uses flexbox layout to align items vertically and horizontally.
  • align-items: center;: Centers items vertically.
  • justify-content: center;: Centers items horizontally.
  • font-family: 'Orbitron';: Specifies the font family for text elements to Orbitron.
  • margin: 0;: Removes default margin.
  • height: 100vh;: Sets the height of the body to 100% of the viewport height.

These CSS styles define the overall layout and appearance of the calculator, ensuring it is centered on the page and uses the specified font.

// Get references to the calculator elements
const display = document.getElementById('display');
const numberButtons = document.querySelectorAll('.number-btn');
const operatorButtons = document.querySelectorAll('.operator-btn');
const clearButton = document.getElementById('clear-display');
const calculateButton = document.getElementById('calculate');

// Variables to store the current calculation
let firstOperand = null;
let secondOperand = null;
let currentOperator = null;
let shouldResetDisplay = false;

// Function to perform the calculation based on the operator
function calculate() {
  let result;
  const first = parseFloat(firstOperand);
  const second = parseFloat(secondOperand);

  switch (currentOperator) {
    case '+':
      result = first + second;
      break;
    case '-':
      result = first - second;
      break;
    case '*':
      result = first * second;
      break;
    case '/':
      result = first / second;
      break;
    default:
      return;
  }

  display.value = result;
  firstOperand = result.toString();
  secondOperand = null;
  currentOperator = null;
}

// Event listeners for number buttons
numberButtons.forEach((button) => {
  button.addEventListener('click', () => {
    if (display.value === '0' || shouldResetDisplay) {
      display.value = button.dataset.value;
      shouldResetDisplay = false;
    } else {
      display.value += button.dataset.value;
    }
  });
});

// Event listeners for operator buttons
operatorButtons.forEach((button) => {
  button.addEventListener('click', () => {
    if (firstOperand === null) {
      firstOperand = display.value;
    } else if (currentOperator !== null) {
      secondOperand = display.value;
      calculate();
    }

    currentOperator = button.dataset.operator;
    shouldResetDisplay = true;
  });
});

// Event listener for clear button
clearButton.addEventListener('click', () => {
  display.value = '0';
  firstOperand = null;
  secondOperand = null;
  currentOperator = null;
});

// Event listener for calculate button
calculateButton.addEventListener('click', () => {
  if (currentOperator === null) return;
  secondOperand = display.value;
  calculate();
  shouldResetDisplay = true;
});

Explanation:

  • let currentNumber = ''; and let operationType = '';: Declare two variables to store the current number being entered and the type of operation to perform.
  • function appendNumber(number) { ... }: Defines a function to append numbers to the current number when a number button is clicked.
  • function appendOperator(op) { ... }: Defines a function to set the operation type when an operator button is clicked.
  • function clearDisplay() { ... }: Defines a function to clear the display by resetting the current number and operation type.
  • function calculate() { ... }: Defines a function to perform calculations based on the operation type selected.
  • function updateDisplay() { ... }: Defines a function to update the display with the current number.

These JavaScript functions add functionality to the calculator, allowing users to input numbers, select operators, clear the display, perform calculations, and update the display accordingly.

This comprehensive breakdown covers the HTML, CSS, and JavaScript components of the simple calculator, providing a clear understanding of how each part contributes to the overall functionality and appearance.


0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Let's Start Your Social Media Success Story Today!

At Ourgrid, we’re committed to helping you achieve your social media marketing goals. Whether you’re looking to boost brand awareness, drive engagement, or increase conversions, our team of experts is here to guide you.

Frequently Asked Questions

Have Questions About Our Social Media Marketing Services? We Have Answers!
What services does your web design agency offer?
  • Our agency specializes in a wide range of services including website design, development, UX/UI design, e-commerce solutions, mobile responsiveness optimization, SEO, and digital marketing strategies tailored to enhance online presence and engagement.
How do you approach the design process for a new website?

Our design process begins with comprehensive research and understanding of your business goals and target audience. We then proceed to wireframing, prototyping, and iterative design, ensuring constant communication and feedback loops with our clients to achieve the desired outcome effectively and efficiently.

What sets your agency apart from others in the industry?

Our agency stands out due to our commitment to delivering high-quality, customized solutions that are not only visually appealing but also functional and user-friendly. We prioritize collaboration with our clients throughout the entire project lifecycle, ensuring their vision is realized while also incorporating industry best practices and the latest design trends.

Can you provide examples of successful projects your agency has completed?

Certainly! We have a portfolio showcasing a diverse range of projects across various industries, each demonstrating our expertise in creating unique and impactful web experiences. From small businesses to large enterprises, our projects consistently deliver results that exceed expectations and drive measurable success.

How do you ensure websites are optimized for search engines (SEO)?

SEO optimization is an integral part of our design process. We employ best practices in website structuring, content creation, keyword research, and metadata optimization to ensure maximum visibility and ranking on search engine results pages. Additionally, we provide ongoing SEO maintenance and analytics tracking to continuously improve performance.

What is your approach to responsive design?

We prioritize responsive design to ensure that websites are accessible and perform well across all devices and screen sizes. Our approach involves utilizing flexible grids and layouts, fluid images, and CSS media queries to adapt the design seamlessly to different viewing environments, enhancing user experience and engagement.

How do you handle website maintenance and updates post-launch?

We offer comprehensive maintenance packages tailored to meet the specific needs of our clients. This includes regular backups, security updates, content updates, performance monitoring, and ongoing support to address any issues or enhancements required post-launch, ensuring the website remains secure, up-to-date, and optimized for continued success.

What is your process for measuring the success of a website after launch?

We utilize a combination of analytics tools and key performance indicators (KPIs) to assess the effectiveness and impact of the website post-launch. This includes tracking metrics such as traffic, engagement, conversion rates, and user behavior to identify areas for improvement and optimization, allowing us to continuously refine and enhance the website’s performance over time.

Empower Your Brand Captivating Audiences through marketing.

Copyright: © 2024 Serpentcoding.com WordPress. All Rights Reserved.

0
Would love your thoughts, please comment.x
()
x
Verified by MonsterInsights