Introduction to (Web) Programming

Lab 7: Arrays and the DOM

shortcut to main problems

Goals


General instructions


I. Console exercises

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>

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 lab7.js, but will also want to look over and make a few changes to lab7.html and lab7.css. You should test your work by loading (and reloading when necessary) lab7.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. Experiment with the three introductory DOM examples we covered in class:
  2. Consider some color options. Set the background-color property (for the body element in lab7.css). Experiment with changing and adding other CSS properties, too.

  3. Examine lab7.html to see how it makes use of a table element. (If you need a refresher, review the basics of HTML tables.)

  4. Add more table data cells (in lab7.html) so that you have at least five (you can have more if you like).

  5. Observe how the table data cell elements (the td tags) have been assigned the class box. Modify the CSS properties (in lab7.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 lab7.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 lab7.html.

  6. 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).

  7. 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 lab7.html that invokes the doubleBoxes function in its onclick attribute, then test your work by clicking the newly added double button.

  8. 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.

  9. 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.

  10. Complete the function selectBox() so that it uses the value property of the text-input element (for lab7.html, that has the unique id attribute 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 parseInt 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.