Lab 6: Arrays and the DOM

Programming the Web: An Introduction

shortcut to main problems


General instructions

I. JavaScript console exercises

Open the JavaScript console in your Web browser (Command-Option-I). Using the browser’s JavaScript console, try these examples, in order, one at a time:

    > undefined
    > typeof undefined
    > undefined === undefined
    > undefined === null

    > let seasons = ['Winter', 'Summer', 'Spring', 'Fall'];   // an array literal
    > seasons.length
    > seasons
    > seasons[0]
    > seasons[3]
    > seasons[4]   // JavaScript is forgiving
    > let aSeason = seasons[1];
    > aSeason
    > let bSeason = seasons[2];
    > seasons[1] = bSeason;   // modifying the array
    > seasons
    > seasons[2] = aSeason;
    > seasons

    // building an array with push
    > let csFaculty = [];   // start with empty array
    > csFaculty
    > csFaculty.push('Jim');
    > csFaculty
    > csFaculty.push('Mike');
    > csFaculty
    > csFaculty.length

    // removing elements with pop
    > let last = csFaculty.pop();
    > last
    > csFaculty
    > csFaculty.length
    > csFaculty.pop()   // this is side effecting!
    > csFaculty.length
    > csFaculty.pop()   // JavaScript is forgiving
    > csFaculty.length

    // using join and split: evaluate expressions like these
    > seasons.join(',')

    > 'the quick brown fox'.split(' ')

II. Accessing and manipulating the DOM via the console

Consider these two ideas:

In the console, try these:

> let span = document.getElementById('lab-example-output');
> span
> typeof span
> span.innerHTML

> document.getElementById('whatever')   // JavaScript is forgiving

> span.innerHTML = 'CHECK THIS OUT!';

Observe the effect of having typed in that last assignment.

Now type something into the above input text field and then try these in the console:

> let textField = document.getElementById('lab-example-input');
> textField
> textField.value
> span.innerHTML = textField.value;

Again, observe the effect of having typed in that last assignment. We can combine those two ideas into a function:

function copyTextFromInputToSpan() {
    let span = document.getElementById('lab-example-output');
    let textField = document.getElementById('lab-example-input');
    span.innerHTML = textField.value;
    textField.value = '';   // clear value from input field

and attach that function to the following button which is created in HTML as:

<button onclick="copyTextFromInputToSpan();">click me</button>

(you may want to scroll up a bit to witness the effect)

III. Class selectors

Here are a few “paragraphs”:

  Good morning. (A boring paragraph.)

  Beware the Jabberwock… (Less boring.)

  How are you today? (Back to boring.)

  The vorpal blade went snicker-snack! (Less boring again.)

  Goodnight. (Yawn.)

The HTML specifying the paragraphs is roughly like this:

<p>Good morning. (A boring paraggraph.)</p>
<p class="cool">Beware the Jabberwock... (Less boring.)</p>
<p>How are you today? (Back to boring.)</p>
<p class="cool">The vorpal blade went snicker-snack! (Less boring again.)*</p>
<p>Goodnight. (Yawn.)</p>

Notice how two of the p tags have class selectors - in this case both are of class cool. A style can be (and has been) given to make the background colors of those two paragraphs slightly different than the rest of the page). We can also use JavaScript to directly modify that style. Try this in the console:

> let coolGraphs = document.getElementsByClassName('cool');
> coolGraphs.length
> coolGraphs[1].innerHTML
> coolGraphs[0].style.backgroundColor = 'MediumOrchid';

Observer that the last assignment modifies the style of the first of those two “cool” paragraphs to change its background color.

Main exercises

For the rest of the lab, you need to download and unzip this archive. It consists of several files. You will mostly work in lab6.js, but will also want to look over and make a few changes to lab6.html and lab6.css. You should look at the examples in array-examples.js. You should test your work by loading (and reloading when necessary) lab6.html in your browser. (You may still find it helpful to tests parts of your work in the console.) You are encouraged to try my solution to see the tasks assigned below in action.

  1. Review some of the introductory DOM examples we have demonstrated in class:

  2. Consider some color options. Set the background-color property (for the body element in lab6.css). Experiment with changing and adding other CSS properties, too.

  3. Examine lab6.html to see how it makes use of a table element. (If you have not yet encountered HTML tables, checkout this basic HTML table tutorial.) Add more table data cells (in lab6.html) so that you have at least five (you can have more if you like).

  4. Observe how the table data cell elements (the td tags) have been assigned the class box. Modify the CSS properties (in lab6.css) for the box class so that table data cells have the same width (not too big, not too small), a background color distinct from the rest of the page and a solid border. (Review border basics.) The table should now appear something like this:

    Most of the remainder of the lab exercises involve working in lab6.js. You should read over the code in that file before proceeding, paying particular notice to the initialize and putArrayInBoxes functions, both which place values into the data cells in the HTML table defined in lab6.html.

  5. Fix randomArray(n, start, stop) so that it constructs and returns a new array consisting of n integers all between start (inclusive) and stop (exclusive). (It is close to working as is.) You can test it in the console as in:

     > randomArray(3, 1000, 2000)

    and you can also (and should) test it by clicking the random button which calls the randomizeBoxes function (which has been provided for you).

  6. Complete doubleArray(a) so that it doubles the numerical value of every element in a. Assume a is an array of numbers. Your function should be side-effecting: it should modify (mutate) a, but not return anything. Add a button to the button-bar section of lab6.html that invokes the doubleBoxes function in its onclick attribute, then test your work by clicking the newly added double button.

  7. Complete swap(a, i, j) so that it modifies array a by exchanging the values of the elements in position i and position j. You can assume a is an array and that i and j are valid indexes (i.e., integers that are at least 0 and less than a.length). Console example:

     > let names = ['Fred', 'George', 'Ginny', 'Percy', 'Ron'];
     > names
       Array(5) [ 'Fred', 'George', 'Ginny', 'Percy', 'Ron' ]
     > swap(names, 1, 3);
     > names
       Array(5) [ 'Fred', 'Percy, 'Ginny', 'George, 'Ron' ]

    You can also test it by clicking on the swap button.

  8. Complete reverseArray(a) so that it reverses the order of the elements of array a. Again, this is side-effecting: it changes a and does not return anything. Test with the reverse button.

  9. Complete the function selectBox() so that it uses the value property of the input element (in lab6.html, the one that has the unique id attribute box-number-input) to choose one of the table cells to “highlight” - by changing its border color to something other than black. (I suggest something bright like red.) To do this, remember that the value property of the HTML element will arrive in JavaScript as a string, so you need to use parseFloat (or Number) before using it to access the particular box to set its style.borderColor property. Test by clicking the select button next to the input field. Optional: make it so that selecting a new box reverts the border color of the previously selected box back to its normal border color.