Create a simple calculator with CSS Glassmorphism

Making a working calculator should be one of the projects to explore while learning to code. Exploring and learning more about Javascript should give you the basic concepts and skills in Javascript.

I made a working calculator with CSS glassmorphism and JavaScript. It is a refreshing and wonderful experience when the equal sign finally gives a correct result, and the long hours of debugging JavaScript are finally worth it. Let me take you through my time while making the calculator and actually how to make the calculator.

Applying CSS glassmorphism.

Glassmorphism is a style that Michal Malewicz first created for Hype4.Academy in around 2019, and since then it has gained popularity within mainstream usage. Big companies such as Apple have started using it on their websites. Let's dive deeper into CSS glassmorphism.

Characteristics and its features.

  • Transparency (frosted glass)

  • Vivid or pastel colors.

  • Light border.

The CSS >backdrop-filter> is majorly used as it allows us to apply multiple effects throughout the design process, such as blur, and grayscale effects to the area behind the component or the main element. For the effect to be visible, the element must be at least partially transparent with a white border-radius and a little more blur on the main element.

Our first line of CCS code should be a semi-transparent background and apply blur using the CSS backdrop-filter property.

Let's have a look at the pieces of CSS code to generate effects of glassmorphism.


   background: rgba( 255, 255, 255, 0.8 );

    box-shadow: 0 8px 32px 0 rgba( 31, 38, 135, 0.37 );

    backdrop-filter: blur( 10px );

    -webkit-backdrop-filter: blur( 10px );

    border-radius: 10px #fff;

    border: 1px transparent;

    position: absolute;

    top: 40px;

    bottom: 50%;

    left: 30%;

    width: 300px;

    height: 450px;

The first six lines of code are my glassmorphism design, and where I want my calculator to be placed in my tab when it's open is the preceding lines.

Glassmorphism is mostly compatible with most of the browsers out there, except for Firefox, where it has to be enabled.

Some of the browsers compatible with glassmrphism include

  • Chrome

  • Safari

  • IOS

  • Android browser and Edge

  • Firefox can be enabled.

Explaining the JavaScript

Let's take a look at my Javascript code in the code snippet below before I move on to explaining each and everything.


let display = document.getElementById('display');

let buttons = Array.from(document.getElementsByClassName('button'));

buttons.map( button => {

    button.addEventListener('click', (e) => {

       switch(e.target.innerText){

           case 'C':

               display.innerText = '';

               break;

            case '←':

             if(display.innerText){

                 display.innerText = display.innerText.slice(e, -1);

                };

                   break;

            case '=':

                try{

                    display.innerText = eval(display.innerText);

                }catch {

                    display.innerText = 'Error!'

                };

                break;

           default:

               display.innerText += e.target.innerText;

       }

    });

});

When defining the elements, I referenced my display dom element to documents.getElementByID because it is saved to an ID of my choosing, Then the buttons I save them to an Array operator .from() method with documents.getElementsByClassName because I save the buttons to a class.

An array is an ordered list of values and it has operators to help in executing functions in Javascript.

I used the array operator .from () method to define the HTML element "buttons". The array.from () has an optional parameter mapFn, which allows us to execute a .map () function on each of the elements of the array created.

The .map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

This calls all the arrays in the HTML element button in order and constructs a new array from the result.

A "callback function" is invoked with three arguments.

  • The value of the element.

  • The index of the element.

  • The array object being mapped.

I added the addEventListener to the function for each button that is clicked.

The addEventListener handles events triggered by user interactions. A more advanced method is to use event bubbling, but since this project is for a beginner, I will use e.target.innerText, which gives back the label that has been clicked and displays it on display.

The switch () statement, Is to select one of many codes to execute. The switch() statement is executed once;

  • The value of the expression is compared with the values of each case, If there is a match, the associated block of code is executed. If there is no match, the default code block is executed.

The break keyword breaks out of the switch block. This stops the execution inside the switch block. If the break keyword is not there, the code will continue running even though the code is wrong. It is not necessary to break the last case in a switch block, The switch block breaks there.

The switch case uses strict comparisons.

  • The values must be the same type to match.

  • A strict comparison can only be true if the operands are of the same type.

With the back button, I used the Javascript conditional statement 'if' in case the back button is pressed by the user. The following code is executed.


  if(display.innerText){

                 display.innerText = display.innerText.slice(e, -1);

                };

The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end, where start and end represent the index of the items in that array.

A negative index indicates an offset from the end of the sequence slice(-1) extracts the last element and returns a new array.

Slice does not alter the original array, It returns a shallow copy of the original array.

e is the short var reference for events object. e is an event handler object in javascript.

e indicates the slice() when executed will return the event and the negative index that is offset.

try-catch block statement.

The try-catch block statement block code is meant to handle any error that would occur during use and to alert the user that there is an error with the input.

eval() is a function property of the global object, I have used the eval() function to execute and run the operation of the calculator. eval() runs the code and returns the result of the last statement. I used eval() because it does not need to check the expression for correctness. Though it is very dangerous to use eval().

The side effect of eval() is that it can access outside variables. In the event a hacker gets on or calculator and passes a fishy website, the user will be redirected to the fishy website, which would put the user at risk.

Thanks a lot for reading. Now go and code your own calculator with your own design.

Resources

For more glassmorphism effects.

Also, check out my codepen for the entire code of the calculator.

codepen.io/Ongeowun/pen/dydzqBe