Calculator Project – Javascript-CSS

This is our final day on our calculator project. This is just for cleaning it up a bit.

We changed the HTML in our code by writing numbers on the screen of our calculator. You can right click on the screen and choose Inspect. You can see your code and watch the HTML change as new numbers are written on the screen.

Today we’re going to use our Javacript to change the CSS. While there are things we could do to shorten our code and make it slicker, I only want to change a couple of things to finish it off. One thing I’d like to do is keep it from typing an operator if there is no number on the screen yet. Mostly that wouldn’t happen, but it would be nice if it couldn’t happen. I am going to use an If Statement to check if num1 is null. If num1 == null, then I don’t want it to write an operator on the screen. I just want it to return. If it is not empty, then we want it to write the operator. We can write that using the code for not equal. If (num1 != null) {then write the operator.} != is how we write not equal to compare two things.

I wanted to do a little CSS work by adding a pointer for the cursor when it was on the numbers. I added this CSS.

#buttons {cursor : pointer;}

The final thing I added isn’t necessary, but it will let us use a new code bit, by changing the CSS using Javascript, meaning, the CSS can change based on what’s being done by the user.

I changed the CSS of the equal sign and the clear button to be the color gray. Then when there is writing on the screen, the clear button turns red. When there is a second number, then the equal sign turns red. I didn’t need any If Statements to accomplish that; I just put it in the code where those things were happening. Then when they are pushed, they turn back to gray to reset.

$(“#equal”).css(‘background-color’, ‘#cc1423’);  /*Turns it red.*/

$(“#clear”).css(‘background-color’, ‘gray’);  /*Turns it back to gray.*/

We could take this further and, like what we did with the operators, keep the user from being able to write an equals sign on the screen if it’s not time. To do that we can read the CSS.

var element = document.getElementById(‘equal’);  /*This says we’re talking about #equal.*/

var style = window.getComputedStyle(element);   /*This says to find the CSS style of #equal.*/

var backgroundColor = “background-color”;   /*I needed a variable for the property I wanted.*/

var buttonColor = element.style.backgroundColor;  /*Creates a variable that is #equal’s color.*/

if (buttonColor == ‘gray’) {   /*If the color is gray, then we don’t want to write = . */

return;

}

If you wanted to go further, you could find the length of the answer and cut it off at a certain length. We won’t go that far in our lessons. You can work with Google for that one.

You can watch the video of this lesson.