CSCI 107 — JavaScript III

Readings

Getting the starter files

Start by downloading an updated ZIPed copy of HTML, CSS, and JavaScript files and store it on your Desktop.

Open up Brackets and connect to the unZIPed directory, which should be called jslab_exp3. Just like the last JavaScript lab, look at the three files, paying particular attention to shakespear.js.

What’s the difference

This time, you should notice that the border around the ”Parting is such sweet sorrow sweet sorrow“ quote changes color every three seconds. This is an example of selection, one of the three components of programming.

This is implemented with three sections of JavaScript code. The first is a statement in startup that sets an interval timer.

    setInterval(changePartingBorderColor, 3000);

The second is an event handler, changeBorderQuote, that makes the changes the border color. Notice how this function, tests the present value of partingBorderColor to determine the new value.

function changePartingBorderColor() {
    'use strict';
    var partingElement = document.getElementById('parting');
    /* This is an example of selection */
    if (partingBorderColor === 'green') {
        partingBorderColor = 'purple';
    } else {
        partingBorderColor = 'green';
    }
    partingElement.style.borderColor = partingBorderColor;
}

The third change is a bit more subtle. Because partingBorderColor must retain its value between calls to changePartingBorderColor, we must declare it outside the body of changePartingBorderColor. This is done with the keyword var.

var partingBorderColor = 'green';

OK. If you read the tutorial on JavaScript scope, you will see that we really didn’t need to declare partingBorderColor at all. However, your program will be easier to read and maintain if you follow good programming practices and declare your variables.

Doing something

Here are some tasks that will make an obnoxious web page. See if you can do some of them.