Level-Up Coding

Level 2: Javascript is a programming language for web pages.

HTML and CSS can define how a web page looks, but they don’t give you a way to change the page after it is loaded in the browser. That’s where Javascript comes in. Instead of defining a fixed layout, the commands in Javascript are executed one at a time from top to bottom, unless something in the code changes that order. Also code in the Javascript can be run in response to events, such as button presses or mouse clicks.

Javascript is one of the most popular programming languages in the world. It controls most of the dynamic content on web pages, and almost all modern browsers support it. Another good thing about it is that you don’t need a lot of special software tools to write Javascript code. You can write Javascript code in a simple text editor and run it in any browswer.


Putting Javascript on a Web Page

Javascript code is placed on a web page inside a <script> element. Just like how CSS looks different than HTML, Javascript looks different too. It has its own syntax and semantics. Let’s look at example of a simple page with some Javascript on it:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Javascript Test</title>
</head>

<body>
    <h1 id="header">Javascript is fun!</h1>
    <button type="button" onclick="changeCounter();">Counter</button>
    <p id="counter">Count: 0</p>

    <script>
    // Define a variable to hold the value of the counter
    var counter = 0;

    // The changeCounter function adds 1 to the count
    var changeCounter = function()
    {
        counter = counter + 1;
        var c = document.getElementById("counter");
        c.innerHTML = "Count: " + counter;
    }
    </script>    
</body>
</html>

The HTML part

The code above is a lot to understand at once, so let’s break it down piece by piece. Most of the code is HTML like we have seen before. It defines what things will be on the page and where they will go. In the <body> element, the page defines three items, a header, a button, and a paragraph:

    <h1>Javascript is fun!</h1>
    <button type="button" onclick="changeCounter();">Counter</button>
    <p id="counter">Count: 0</p>

This is mostly the same as the HTML you have seen before, but there are a few differences. One thing to notice is that the paragraph <p> element has an id attribute. The Javascript code will later look up the paragraph element using the id.

A second thing to notice about the code is the <button> element. This element will show as a button on the screen that can be clicked with the mouse.
In the button tag there is an onclick attribute with the value "changeCounter();". This is Javascript code that will run every time you click on the button. What it does is to call the function changeCounter, so that the code inside it will run.


The Javascript part

After the HTML part of the page, the main Javascript code is given in a <script> element. Everything in-between <script> and </script> is written in Javascript instead of HTML. As mentioned earlier, this means that the syntax rules about what kinds of things you can put in the script element are different from the rules you use when you write the rest of the HTML document. So really, the page is written in two different languages, and if we included a CSS style sheet, the page would contain three different languages!


Javascript variables

Let’s look at the different parts of the Javascript code from the example above. The first two lines are the following:

    // Define a variable to hold the value of the counter
    var counter = 0;

The line that starts with a double slash // is called a comment. Comments are ignored by the browser, but they are there to help you understand and remember what the code does. In this case, the comment tells us that the next line defines a variable to hold the value of a counter. Writing good comments in your code can be very helpful. Comments that start with // are called single-line comments, since they go to the end of the line they start on. Multi-line comments can be written as well. These start with /* and end with */.

The next line declares a variable called counter, and sets its value to the number 0. You can think of a variable as a storage bin in the computer with a label on it where some data can be stored. The label is called the name of the variable, and the data inside the bin is called the variable’s value.

Each piece of data in the computer has a type. Some of the types that Javascript variables can hold are

In the line var counter = 0;, the keyword var tells the computer that we are declaring a variable. The equals sign (=) is called the assignment operator. It tells the computer to copy the value on the right side of the equals to the variable on the left side. Finally, the semicolon (;) at the end of the line acts to separate different code statements. Think of it like the period at the end of a sentence. In Javascript, the semicolon is optional, but we use it in our examples since it is required in some other languages.


Javascript Functions

The next part of the Javascript code defines a function. A function is a group of code statements that are grouped together. These can be run by calling the function from another part of the code, and this is what we saw earlier in the onclick property of the button. The code below defines a variable called changeCounter and sets its value to a function.

    var changeCounter = function()
    {
        counter = counter + 1;
        var c = document.getElementById("counter");
        c.innerHTML = "Count: " + counter;
    }    

The code of the function begins and ends with curly braces {}. This helps the computer know where the function code starts and stops. When a function runs, it executes one statement at a time, going from top to bottom, unless something changes the ordering. (The main things that can change the execution order are function calls, if statements, and loops. We will discuss if statements and loops in later lessons.)

The code statement counter = counter + 1; adds 1 to the counter variable that was defined earlier, and the result is stored back into the counter variable because of the assignment operator (=).

The next statement is a little more complicated: var c = document.getElementById("counter");. This line creates a variable called c to hold a reference to the paragraph tag that was defined earlier in the HTML code. You can do this because Javascript has a built in function called document.getElementById. We pass in the name of the element we want in parentheses () to the function, so that it knows what element to get.

The final line of the function c.innerHTML = "Count: " + counter; changes the html of the paragraph element to be the String Count: followed by the number counter. You may have noticed that in the first line of the function we added 1 to a number, and got back another number, but here, the code adds a string to a number and gets a string back. This is an example of what is called operator overloading, or in other words, using the same symbol to mean different operations depending on the context.


Terms


Exercise

  1. Copy the example page from the top of this lesson to a text file and save it to your computer with a .html extension.

  2. Put another button in the HTML part of the page. Make the new button call a different function named changeHeader.

  3. Write a function called changeHeader in the Javascript part of the page. Make the new function change the header in some way, such as adding an exclamation point at the end.

  4. Test your new page to make sure that both of the buttons work.


Bonus Level: Adding some CSS