Create a simple calculator using HTML, CSS and Javascript

Summarize

Git is a distributed version control system DVCS designed for efficient source code management, suitable for both small and large projects. It allows multiple developers to work on a project simultaneously without overwriting changes, supporting collaborative work, continuous integration, and deployment. This Git and GitHub tutorial is designed for beginners to learn fundamentals and advanced concepts, including branching, pushing, merging conflicts, and essential Git commands. Prerequisites include familiarity with the command line interface CLI, a text editor, and basic programming concepts. Git was developed by Linus Torvalds for Linux kernel development and tracks changes, manages versions, and enables collaboration among developers. It provides a complete backup of project history in a repository. GitHub is a hosting service for Git repositories, facilitating project access, collaboration, and version control. The tutorial covers topics such as Git installation, repository creation, Git Bash usage, managing branches, resolving conflicts, and working with platforms like Bitbucket and GitHub. The text is a comprehensive guide to using Git and GitHub, covering a wide range of topics. It includes instructions on working directories, using submodules, writing good commit messages, deleting local repositories, and understanding Git workflows like Git Flow versus GitHub Flow. There are sections on packfiles, garbage collection, and the differences between concepts like HEAD, working tree, and index. Installation instructions for Git across various platforms Ubuntu, macOS, Windows, Raspberry Pi, Termux, etc. are provided, along with credential setup. The guide explains essential Git commands, their usage, and advanced topics like debugging, merging, rebasing, patch operations, hooks, subtree, filtering commit history, and handling merge conflicts. It also covers managing branches, syncing forks, searching errors, and differences between various Git operations e.g., push origin vs. push origin master, merging vs. rebasing. The text provides a comprehensive guide on using Git and GitHub. It covers creating repositories, adding code of conduct, forking and cloning projects, and adding various media files to a repository. The text explains how to push projects, handle authentication issues, solve common Git problems, and manage repositories. It discusses using different IDEs like VSCode, Android Studio, and PyCharm, for Git operations, including creating branches and pull requests. Additionally, it details deploying applications to platforms like Heroku and Firebase, publishing static websites on GitHub Pages, and collaborating on GitHub. Other topics include the use of Git with R and Eclipse, configuring OAuth apps, generating personal access tokens, and setting up GitLab repositories. The text covers various topics related to Git, GitHub, and other version control systems Key Pointers Git is a distributed version control system DVCS for source code management. Supports collaboration, continuous integration, and deployment. Suitable for both small and large projects. Developed by Linus Torvalds for Linux kernel development. Tracks changes, manages versions, and provides complete project history. GitHub is a hosting service for Git repositories. Tutorial covers Git and GitHub fundamentals and advanced concepts. Includes instructions on installation, repository creation, and Git Bash usage. Explains managing branches, resolving conflicts, and using platforms like Bitbucket and GitHub. Covers working directories, submodules, commit messages, and Git workflows. Details packfiles, garbage collection, and Git concepts HEAD, working tree, index. Provides Git installation instructions for various platforms. Explains essential Git commands and advanced topics debugging, merging, rebasing. Covers branch management, syncing forks, and differences between Git operations. Discusses using different IDEs for Git operations and deploying applications. Details using Git with R, Eclipse, and setting up GitLab repositories. Explains CI/CD processes and using GitHub Actions. Covers internal workings of Git and its decentralized model. Highlights differences between Git version control system and GitHub hosting platform.

2 trials left
In this tutorial we will create a fully working calculator using only HTML, CSS and vanilla Javascript. You'll learn about event handling, and DOM manipulations throughout the project. In my opinion this is a really good beginner project for those who want to become web developers.

HTML

The html will be pretty simple for this project. We'll start out with a standard HTML5 boilerplate. At the bottom of our body I included the index.js script that we will create later. This needs to be at the bottom, because this way, when our javascript runs, the html elements required for the calculator will be in the DOM. In the body we have a section and inside that a div with a container class. We will use these wrappers to position our calculator on the page. Inside our container we have an empty div with the id of display, and this will be the display of our calculator. It is empty, because we will modify its content from Javascript. Then we have a div with the class of buttons which will represent the keypad of the calculator.

<body>
   <section>
     <div class="container">
        <div id="display"></div>
          <div class="buttons">

          </div>
     </div>
   </section>
<script src="index.js"></script>
</body>
The buttons container will hold all of the buttons. Each button will be a div with a class of button. This will make the styling easy, and also will help us to gather the user input. Here we have a div for every button that we want on our keypad. You can notice that we have a weird looking label between the buttons: &larr;. This is a HTML entity and it renders a back arrow (←), and we'll use this as a backspace. Also please not that for the equal sign button we have a separate id equal. We will use this Id to distinguish this special button, and evaluate the expression provided to the calculator.

<div class="buttons">
  <div class="button">C</div>
  <div class="button">/</div>
  <div class="button">*</div>
  <div class="button">←</div>
  <div class="button">7</div>
  <div class="button">8</div>
  <div class="button">9</div>
  <div class="button">-</div>
  <div class="button">4</div>
  <div class="button">5</div>
  <div class="button">6</div>
  <div class="button">+</div>
  <div class="button">1</div>
  <div class="button">2</div>
  <div class="button">3</div>
  <div class="button">.</div>
  <div class="button">(</div>
  <div class="button">0</div>
  <div class="button">)</div>
  <div id="equal" class="button">=</div>
</div>
And this is all of the HTML markup that we need for this project, let's jump into CSS. Don't forget to link the CSS styleshead in the head of the HTML file:

<link rel="stylesheet" href="style.css">

CSS

Let's create a style.css file. We set a width for the container and center it using margin (also give it a decent top margin of 10vh), and apply a little box shadow.

.container {
    max-width: 400px;
    margin: 10vh auto 0 auto;
    box-shadow: 0px 0px 43px 17px rgba(153,153,153,1);
}
For the display we set a fixed height, and to center the text vertically we need to set the line-height to the exact same amount. The text should be right align, because this is how most calculator displays work. Also set the font-size and give a decent amount paddings.

#display {
    text-align: right;
    height: 70px;
    line-height: 70px;
    padding: 16px 8px;
    font-size: 25px;
}
To position the buttons we use CSS grid. By setting 4 x 1fr in-grid-template-coloumns we'll have 4 equally sized buttons in each row. We only set bottom and left borders, so we won't get double borders. We'll set the other two sides in the next CSS rule.

.buttons {
    display: grid;
    border-bottom: 1px solid #999;
    border-left: 1px solid#999;
    grid-template-columns: 1fr 1fr 1fr 1fr;
}
Apply the missing two sides of the borders for every button:

.buttons > div {
    border-top: 1px solid #999;
    border-right: 1px solid#999;
}
For the button we'll set borders, font-size and 100px of line height to center it vertically, and set text-align: center to center the button labels horizontally. To have a better user experience set cursor to pointer, so the user will know that this is a clickable element.

.button {
    border: 0.5px solid #999;
    line-height: 100px;
    text-align: center;
    font-size: 25px;
    cursor: pointer;
}
We want the equal button to stand out so, we'll set a blue background color and white text to it. Also to have a nice hover effect we'll set a darker background color and white text color on hover. To make the transition smoot set: transition: 0.5s ease-in-out;.

#equal {
    background-color: rgb(85, 85, 255);
    color: white;
}

.button:hover {
    background-color: #323330;
    color: white;
    transition: 0.5s ease-in-out;
}

Javascript

This will be the heart of our application. Let's create the index.js file. The first thing we need to do is to save a reference to our display dom element. We can easily do that because it has an id of display.

let display = document.getElementById('display');
Next we have to get references for the buttons. We'll store the button references in an array. To gather the buttons we can select them by document.getElementsByClassName('button'), but this function gives back a NodeCollection instead of an array so we have to convert it to an array using Array.from().

let buttons = Array.from(document.getElementsByClassName('button'));
The next and last step we have to make is to add event listener to the buttons and build the functionalities. To add event listeners for the buttons, we'll map through the buttons array and add a click event listener for each. (An advanced solution would be to only add event listener to the buttons container and use event bubbling but this is a more beginner-friendly solution.) To determine what should we do, we'll use e.target.innerText, which will simply give back the label of the button that was clicked. In the first case, when the user hits the "C" button we'd like to clear the display. To do that we can access our display reference and set the innerText to an empty string. Don't forget to add break; at the end, because it is needed to prevent the execution of the code defined in other case blocks. For the equal button we'll use javascript built in eval function. We need to provide the display's content to eval and it will evaluate and return the result, so we should set the result of the eval call to the display's innerText. We need to wrap this into a try catch block to handle errors. Erros can happen when we have syntactically wrong math expressions, for example //(9(, ine these cases we'll set the display's innerText to display 'Error'. ⚠️ You should not use eval in user facing applications, because it can be abused and external code can be run with it. More details If you want to replace eval I suggest using Math.js lib. If the user hits the back arrow we need to remove the last character from the display's innerText. To do that we'll use the String.slice() method, but we only want to do that if the display has any value. Also Read : DA PA Kya Hai ? How to Boost It in Hindi In the default case, so whenever the user don't hit these special symbols we just want to append the clicked button's innerText to the display's innerText. We can use the += operator to do that.

buttons .map( button => {
    button.addEventListener('click', (e) => {
        switch(e.target.innerText){
            case 'C':
                display.innerText = '';
                break;
            case '=':
                try{
                    display.innerText = eval(display.innerText);
                } catch {
                    display.innerText = "Error"
                }
                break;
            case '':
                if (display.innerText){
                   display.innerText = display.innerText.slice(0, -1);
                }
                break;
            default:
                display.innerText += e.target.innerText;
        }
    });
});
The whole project is available on GitHub And that's it you have a working calculator.
 

You may also like this!