Javascript Intro

Calculator Project Part 3

We’re going to start working on making our calculator do something. The first thing we’ll do is something I use Javascript for the most. That thing is that when something is clicked on then I want something to happen.

First, the code needs to know what is clicked on. We’ll use IDs for that. We’ll tell it to look for a certain ID. When that ID is clicked, then we’ll tell it what to do. In our case, when the one button is clicked on, we want it to write a 1 on the screen.

Here’s the code.

document.getElementById("num1").onclick = function write1() {document.getElementById("screen").innerHTML = "1"; } document.getElementById("clear").onclick = function writeClear() {document.getElementById("screen").innerHTML = ""; }

It’s looking at our page (document) and finding the ID “num1.” I had to add id=”num1″ to the 1 button. It doesn’t like just having a number for an ID, so add those letters in there.

Then it says when it’s clicked, do this function. A function is just something to do. Functions are named, followed with the double parentheses (), and then the stuff do to is all combined inside the curly brackets {}.

The thing to do is to find the element of the screen labeled as “screen” and then to write in the HTML the number 1.

The next part is the same exact thing, but it is looking for what is labeled with the ID of “clear” and when that element is clicked, then the HTML is going to be blank. It’s going to write in nothing. That’s the quotes with nothing inside.

You can add IDs to each button in your HTML and add in code like this to make them each write something.

For the CSS, I had to change the class of “clear” to ID of “clear”, since I changed that in the HTML to get that clear button by its own ID. I also added a font size of 2rem and a display of flex. Adding that enabled me to use justify-content: flex-end to get the numbers to show up at the right side of the screen and then align-items: center, gets the numbers centered vertically on the screen.

If something doesn’t work, right click on the screen and choose to inspect element. Then click on “Console” on the screen that shows up. That will list for you any errors it is finding in your javascript. It will tell you what’s wrong and where. It will give you the line number for the code where it’s running into trouble.

If you get it all working, you should still notice a problem. Each number just writes over the last one. We’ll fix that, but not this lesson.

You can watch this lesson.