Category Archives: Uncategorized

Appendix: Various Features

We introduce some features that may be useful for the final project.

Iteration by Timer Events

We have learned how to call a function by a timer in Exercise 06-10. In addition, we can call a function repeatedly without any interaction.

An interval timer invokes a JavaScript function repeatedly with a certain interval.

To set the timer, execute:

  • variable = setInterval(function, interval);

function is the function name and interval is a number representing the interval in millisecond. The ID of the timer is stored into variable – this ID is used when you need stop the timer.

To stop the timer, execute:

  • clearInterval(timerID);

A sample program is shown below. (We assume an image file picture.jpg exists in the same directory)

  • interval.html
  • interval.js

funtion in setInterval can be specified with a function name alone. So, the 6th line above is equal to:
timerId = setInterval(change, 100);

Random Number

Calculation using a mathematical formula should always result in the same output when the inputs are constant. However, in some computer program, it is more convenient when we can get different values each time we calculate. As an example, random numbers are essential in video games in order to randomize the enemy’s behavior.

Random numbers are a sequence of numbers that are unpredictable. In JavaScript, a function Math.random() calculates (pseudo) random numbers. Math.random() allows different numbers to be generated each execution.

Math.random() returns a decimal number no less than 0 and less than 1. In case we want to get a random element of an array, we need an integral random number. To convert decimal to integer, we use multiplication and a round-down function Math.floor(). For example, to get an integer between 0 and 9, execute:

  • Math.floor(Math.random()*10)

Below is a smaple program to display one of rock, paper and scissors randomly.

  • random.html
  • random.css
  • random.js
  • We can rewrite random.js as follows:

No.11 Array


What is an array?

When we have a set of data of a single type, it is more convenient to number each data than naming them one by one. An array can be used to store multiple values (called elements of the array) in a single variable. In order refer to a specific element in an array, it is required to refer to its own index number.

Exercise 11-1(☆)

Execute the following with console.

  • var x = ['Alice', 'Bob', 'Carol'];
  • x[0]
  • x[2]
  • x[3]
  • x[2] = 'Charlie';
  • x[2]

Square brackets “[ ]” are used in the following two manners.

  • To specify an array as a whole – a set of data is written inside a pair of square brackets using commas as separators. The first line of Exercise 11-1 is declaring an array that consists of three strings 'Alice', 'Bob', and 'Carol'.
  • To specify an element of an array, we use an expression like x[0] where variable x is an array and the number 0 inside the bracket is the index of the element. Note that the index of the first element is 0. Therefore, x[0] refers to 'Alice'.

Assignments also have two forms.

  • The first line of Exercise 11-1 stores the entire data into a variable x.
  • In the fifth line of Exercise 11-1, x[2] = 'Charlie' replaces 'Carol' (an element of index 2) to 'Charlie'. In this case, the index has to be referred to specify a particular element inside the array.

Iteration and Array

Arrays are useful because a number of data can be processed in turn, by setting the index as a variable and changing its value using a loop.

Let’s make a calendar as a practice. Dates can be easily modified using increments, but days of week are difficult as they are strings. Therefore, an array can be used to store the days (“Sun”, “Mon”, “Tue”, …) so that we can use the index 0, 1, 2, … instead of the strings directly.

Exercise 11-2(☆☆☆)
  1. Similar to Exercise 09-5, we will create items (li elements) with “Date 1”, “Date 2”, “Date 3”, … in a list (ul elements). Create ex11-2.html and ex11-2.js and fill in the following code.
  2. How does the diagram below correspond to the code above? How does the value of the variable x change as it loops?
  3. Execute the following with console.
    • var day = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
    • var n = 1;
    • day[n]
    • n = n+1;
    • day[n]
    • n = n+1;
    • day[n]
  4. Modify ex11-2.js to print “Date 1 (Mon)”, “Date 2 (Tue)”, “Date 3 (Wed)”. What happens after “Date 7”?
  5. To make it work you can write all 31 elements, 'Sun', 'Mon', 'Tue', ... inside one array. Alternatively, we can use a division remainder (% operator) to specify the day of the week. Execute the following with console.
    • 7 % 7
    • 8 % 7
    • 9 % 7
    • 14 % 7
    • 15 % 7
    • 21 % 7
    • 22 % 7
  6. Rewrite the program so that the day of the week is shown correctly for every day until 31 using a % operator.

Let’s make the calendar more practical.

Exercise 11-3(☆☆☆☆☆)
  1. Create a new text field for “What month”. Corresponding to the input, days should be shown until 28, 30, or 31. (Hint: Use an array for numbers of days in months [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31])
  2. Create another new text field for “What year”, and make a correct calendar. (Hint: Use Zeller’s congruence.)
  3. Use a table instead of a list to show the calendar. (Click here for a sample, but some of its functions are beyond the scope of this course…)

Manipulating Multiple HTML Elements

document.getElementById() is used for specifying a single HTML element. For example, document.getElementById().innerHTML reads/writes the content of an element, and document.getElementById().value gets data from a text field. document.getElementById() always refers to a single HTML element because each id="..." attribute holds a unique name.

In contrast, document.getElementsByTagName() can refer to multiple HTML elements, where the tag name should be indicated in the parentheses. Since there may be multiple elements using the same tag name, document.getElementsByTagName() can be used when it is required to refer to all of them. We usually store them into a variable as an array, and manipulate one of them with some operation such as innerHTML.

Exercise 11-4(☆)
  1. Open SFC-SFS Login Page with a browser.
  2. Display the source of the page, and look for li elements.
  3. Execute the following in console to understand how document.getElementsByTagName() works.
    • var x = document.getElementsByTagName('li');
    • x[0].innerHTML
    • x[1].innerHTML
    • x[4].innerHTML
  4. The number of li elements in the page is equal to the number of elements in the array. Execute x.length in console – length is a property that returns the number of elements in an array.
  5. Open scratchpad from the Firefox browser, and execute the following program in it. What happens to the page, and why?
  6. We can also manipulate input elements in the same way. Execute the following in scratchpad.

In fact, this page has 4 input elements. The fourth element has an attribute type="hidden", which is not shown on screen. The role of hidden input elements is to hold data that will be sent to a web server. To understand this, you must learn about communication between a web browser and a web server, which is covered by FUNDAMENTALS OF INFORMATION TECHNOLOGY 2.

Radio Button

Radio buttons are useful when representing a selection of one item from a list of items.

  • An input element with an attribute type="radio" creates a radio button.
  • Each item in the list will require an input element.
  • The name attribute inside each element groups the radio buttons. For example, suppose we have items such as ‘Policy Management’, ‘Environment and Information Studies’, ‘1st grade’, ‘2nd grade’, ‘3rd grade’ and ‘4th grade’. In order to distinguish those items into two different groups, it is essential to keep the values of the name attributes of ‘Policy Management’ and ‘Environment and Information Studies’ the same, and ‘1st grade’, ‘2nd grade’, ‘3rd grade’ and ‘4th grade’ the same.

In JavaScript, it is required to get the radio buttons in order to check the selected radio button. getElementByID gets only one button and getElementsByTagName will get all input elements that are not radio buttons. Instead, getElementsByName (where the value of the a name attribute is specified in the parentheses) is used to get a group of radio buttons.

Exercise 11-5(☆☆☆)
  1. Create ex11-5.html and fill in the following.

  2. Display the file with a browser, and execute the following in console.
    • var x = document.getElementsByName('faculty');
    • x[0]
    • x[0].value
    • x[1]
    • x[1].value
  3. The value of RadioButton.checked (true or false) indicates whether the button has been selected or not. First execute x[0].checked in console when none of them are selected, and then execute it again after selecting ‘Policy Management’.
  4. true or false can be used in if statement. Execute the following program in console after selecting ‘Policy Management’, and then execute them again after choosing ‘Environment and Information Studies’.
    • var f = 'Unknown';
    • if (x[0].checked) { f = x[0].value; }
    • alert(f);
  5. Create ex11-5.js and fill in the following code. Choose ‘Environment and Information Studies’ and click the button ‘Click here’. Explain the operation of the program.
  6. Rewrite the program so that the faculty is displayed with the student year(1st, 2nd, 3rd or 4th year), e.g., “PM 1st”.
Points to Check
  • What is an array?
  • What does x[0] mean?
  • What is the difference among getElementByID, getElementsByTagName, getElementsByName?

No.10 How a computer works

The Mechanism of a Computer

A washing machine washes clothes using a motor, and a rice cooker heats up rice using a heater.  How does a computer work?

(Download PPT)

Template for “Spec of PC” (DOC | PDF)

Exercise 10-1(☆)
  1. When buying a beverage from a vending machine, what is the input, what kind of process is being executed and what is the output?
  2. In Exercise07-5, what is the input, process and output.
Exercise 10-2(☆☆☆)
  1. On Exercise 09-5, where are ex09-5.html and ex09-5.js stored ? Primary or secondary storage?
  2. When the “pocket” button is clicked, another “Inside the pocket, there’s two cookie” shows up. In which memory is this message saved on?
  3. When the page is reloaded, the screen returns to a single “Inside the pocket, there’s one cookie”. What happened to the data in the primary and secondary memories?
Exercise 10-3(☆)
  1. Start up the Activity Monitor(Applications→Utilities).
  2. The usage of the CPU is displayed under the “CPU” tab.  Open any application and see what happens.
  3. Check the disk activity monitor.  Open any application and see what happens.

With Windows8, the CPU usage can be displayed with the Task Manager

Operating System

The Operating System(OS) is software to manage the computer.  The basic functions of an operating system are:

Process Management
Manages the start-up, execution, termination of software.
Device Driver
The device driver manages parts of input and output to simplify the application.
File System
The unit “file” and “directory” is used to manage data easily on secondary memory.
Manages accessing authorization of data and hardware.
User Interface
A computer is operated by GUI and CUI.

Commonly used operating systems are:

Windows, MacOS, Linux(Ubuntu, etc)
Smart Phone
iOS, Android (Linux is used for kernel)
Windows Server, Unix(Solaris, etc), Linux(RedHat, etc), Mainframe(z/OS, etc)

Process Management

The state of an application being executed is called a “process”.  The operating system manages processes, and terminates programs accordingly.

Exercise 10-4(☆☆)
  1. Start up the activity monitor and check what processes are in motion.
  2. Click “%CPU”, and line the processes in order of CPU usage.
  3. Operate the browser and editor and see if the order changes.
  4. Terminate a process by clicking on the apple mark.
  5. A warning should come up.  Explain what this means from the point of view of primary and secondary memory.

Processes can be terminated on Windows8 with the task manager.

File System

We studied about file systems in Lesson 3, and the main points are:

  • Contents of secondary storages are managed by directories (folders) and files.
  • Two files with the same name can be made if their directories are different.  To distinguish files of the same name, we need to use path names (absolute or relative).
Exercise 10-5(☆☆)
  1. Create ex10-5.txt inside the directory “fundamentals of information technology” we made (or any other directory you like), and write something in it.
  2. Confirm the absolute path of ex10-5.txt via editor.
    • With Atom, click the file name on the bottom left
    • With Emacs, the command M-x pwd will show the directory.
  3. Copy ex10-5.txt (drag with holding the option key) to the desktop.
  4. Open the file and compare the absolute path from before.
  5. Write a different text from the original file and save it.
  6. Did the content of the original file change?
  7. Make an alias of ex10-5.txt(option key + command key + drag, or right click the file and select “Make Alias”)
  8. Open the alias and change the content.
  9. Did the content of the original file change?
  10. Delete the original file.
  11. What happens when the alias is opened by the editor?
  • Copy will create a different file with the same content.  Files with the same name will be treated as a different file as long as they exist in different directories.
  • Alias adds a different name for the same file.  Even if the file name is different, it is still the same file.

In some cases, you don’t want other users to be able read and write your data. In that case, you change the file permissions.


Normally, users work on their own directory and set the accessing authorization so that other users can’t overwrite any files.  However, a file can be shared to the public by changing the permission.  Let’s use the shared region and practice.

Exercise 10-6(☆☆☆☆)
  1. Create ex10-6.txt write something in and save the file.
  2. Select “Move to…” from from Finder and display the content of /pub/sfc/ipl/info1-free.  This is a shared region where anyone can make files.
  3. Move ex10-6.txt to /pub/sfc/ipl/info1-free.
  4. If the file with the same name has already been made by someone else, the file cannot be moved(because you don’t have the authorization to overwrite files.)  Change the file name and try moving the file.
  5. Ask the file name of your neighbor’s, and try opening the file with a editor.  What happens when you change the content and save the file?
  6. Right-click the file and select “Get Info”
  7. On the buttom of the info window, there is “Sharing and Permission” section.  “Everyone” is the column of authorization for other users.  What is it set to?
  8. Ask your neighbor to change the authorization of “Everyone” to read/write, and see if you can edit the file now.

Reviewing if statements and Loops

We studied if statements and loops before.  Now, let’s try combining the two.

There is a game called Fizz Buzz.  We count up from the number 1, and when the number is divisible by 3 we say “Fizz”, “Buzz” when the number is divisible by 5 and “Fizz Buzz” when the number is divisible by both 3 and 5.  Try doing this with your computer.

Exercise 10-7(☆☆☆)
  1. Edit Exercise 09-6 and display numbers from 1 to 30 in order (use a loop).
  2. How should we draw the flowchart (the diagram below) of the program? What goes into the condition and the process part?
  3. First, be able to display “Fizz” when the number is divisible by 3.  Where should we place the conditional branch(in the flowchart)?
  4. Make an if statement of the flowchart you drew.  The condition “divisible by 3” is written in a program as “when the remainder of a number divided by 3 is 0”.  The operant of a remainder is “%”.  When we want to find out the remainder of a variable named “count” when divided by 3, we write count % 3.
  5. Display “Fizz Buzz” when the number is divisible by 3 and 5.
  6. Display “Buzz” when the number is divisible by only 5.
Exercise 10-8(☆☆☆☆☆)

Display numbers from 1 to 99, and add “Ooops!” after numbers in case:

  • The number is divisible by 3.
  • The number contains 3 either on the one’s or ten’s place (such as 13 and 38).

If possible, use only one “if” statement. (Make a condition with logical operators)

Points to Check
  • What 5 functions are there in a computer.
  • How can we measure the performance of a CPU?
  • What is the difference of a primary and secondary memory?
  • What is a process?
  • Why is the access authorization set?

No.9 Loop

Changing Values Stored in a Variable

Calculation using the Current Value

Values can be stored into variables by the process called assignment.


When assigning values to a variable, the pre-assigned value in the variable can be reused. For example, the assignment statement below assigns x+1 to variable x.

  • x = x + 1;

Assuming the pre-assigned value of variable x is 2, x + 1 (which is 3 in this case) will be assigned back to x. Therefore, the new value of variable x will be 3.

Exercise 09-1(☆)
  1. Execute the following statements in a browser console.
    • var x = 3;
    • x = x + 1;
    • x = x + 1;
    • x = x + 1;
  2. Execute the following statements in a browser console.
    • var x = 1;
    • x = x * 2;
    • x = x * 2;
    • x = x * 2;
    • x = x * 2;

Applying mathematical operations on the value itself requires to type the same variable name twice which is sometimes inconvenient. Instead, assignment operators such as +=, -=, *= and /=  can be used to shorten the line.  For instance, x = x + 1 can be written as x +=1. Similarly, x = x – 1 can be written as x -=1.  There is a special operator for incrementing (++x) and decrementing (--x) a value – no difference between x = x + 1, x+=1 and ++x. Alternatively, x++ is also an increment operator which is slightly different from ++x. (see the reference below for detail).

How to use the Debugger

A debugger can be useful to check the current line of execution, or to check the currently stored value inside a specific variable.

What can debuggers do?

Pausing a Program, Step-by-step Execution, Resume
The program can be stopped by setting a breakpoint in a code.  You can also resume the program or execute the program step-by-step.
Displaying/Changing the Value of a Variable
The variable can be displayed/changed when the program is paused at a breakpoint.
Exercise 09-2(☆☆☆)
  1. Create ex09-2.html and fill in the following code.
  2. Create ex09-2.js and fill in the following code.
  3. Click the button several times.  What happened to the number?
  4. Watch the video below to continue the exercise.
  5. Open ex09-2.html via Firefox, and select Tools→Web Developer→Debugger
  6. The left section shows the files used in the webpage,  and the JavaScript program will show up when you click ex09-2.js.
  7. A breakpoint can be set by clicking on the number of the line you want to stop.  Click on the 5th line and make a breakpoint right before alert.
  8. Click on the “execute” button(on the webpage, not the debugger), and call out addCount(). What changed on the debugger screen?
  9. The value of variables are displayed on the right section of the debugger.  The term “scope” is a bit too technical and won’t be explained in this class, but when a variable is declared inside a function it is a local scope, and when a variable is declared outside the function it is called a global scope.  Click on the triangle next to “Global Scope” and check the value of count.
  10. Clicking on the triangle above the file list will resume the program execution.  Resume the program and check whether the value stored in count and the number displayed on the dialog box are equal.
  11. Click on the 4th line and make a break point before count = count + 1.
  12. Click on the “execute” button to call out addCount(), and check the value of count.
  13. Resume the program.  It will stop again at the 5th line, so check the value of  count.
  14. Resume the program and check what number has been displayed in the dialog.
  15. You can remove the break points by re-clicking the numbers. Remove the break points on the 4th and 5th line.


Manipulating the Elements in HTML

In Exercise 08-8, the width of the image was set to 800 when the button was clicked. Let’s change the function so that the width gets 10 pixels larger each time the button is clicked.

Exercise 09-3(☆☆☆)
  1. Create ex09-3.html and fill in the following code.
  2. Create ex09-3.js and fill in the following code.
  3. Open the file via browser and click the button.
  4. Declare a variable w on the top of ex09-3.js and assign the value 100.
  5. In setAttribute, change the width size from the number '800' to the variable w.
  6. Modify the function change() by adding a statement that “adds 10 to variable w“, so that the image gets larger each time the button is clicked.
Exercise 09-4(☆☆☆☆)

Create a text-box and add a function so that the image width changes by the input. So if you enter 100, the width increases by 100.

Adding Content to a Page

In Exercise06-8, we learned that the content of HTML elements can be modified by using innerHTML. Assigning different values into innerHTML each time allows you to constantly change the content.

Exercise 09-5(☆☆☆)
  1. Create ex09-5.html and fill in the following code.
  2. Create ex09-5.js and fill in the following code.
  3. Open the file via browser and click the button.  What happened?
  4. On the 2nd and 3rd line of ex09-5.js, what was assigned to variable x?
  5. What happened to the structure (the relationship of ul and li) of the HTML?
  6. Click the button several times.  Did the number of cookies increase?
  7. Initialize a variable b at the top of ex09-5.js to store the number of cookies.  Assign 1 for its initial value.
  8. Change “there’s one cookie” to “there are n cookies”. The value of variable b should go into the place of “n”.
  9. Add a statement in knock() that adds 1 to variable b.
  10. Reload the page, click the button and check if the number of cookies increase.

Loops and Iterations

In the exercise above, we had to click the button every time to execute the same code again.  A loop can be used to execute a block of code number of times.

“while” Loop

To run the same code over and over, we use the “while” loop.  The syntax of a while loop is as written below.

  • while ( condition ) { process }

If the specified condition is true, the process will be executed. The condition will be checked each time before looping back, and the code will get looped as long as the condition is true . while-207x300

Exercise 09-6(☆☆☆)
  1. Create ex09-6.html and fill in the following code.
  2. Create ex09-6.js and fill in the following.
  3. What is different from the program in Exercise 09-2?
  4. Open the file and click the button.  The page can be reseted by reloading.
  5. If the condition of a while loop is always true, the process will be repeated endlessly.  Change the condition from “true” to when “the counter is less than or equal to 5”.
  6. Reload the page, and click the button.  What is the first and last number?
  7. Swap the 5th(add 1 to count) and 6th(alert) line of ex09-6.js.
  8. Reload the browser, and click the button.  What is the first and last number?  Why is it different? Use the debugger and set breakpoints on line 5 and 6, check the value of count and check if you were right.
Exercise 09-7(☆☆☆☆)

Modify Exercise09-5 to add 100 lines, until “Inside the pocket, there are 100 cookies”, by only one click.

Exercise 09-8(☆☆☆☆)

Make a textbox, and add a function which repeats the process until the number of cookies reaches the input number.

You may think images, such as in Exercise 09-3, can be modified larger and larger by the use of while loop. However, the code inside a while loop gets executed in a very short time which ends up displaying the largest photo only. The proper way to larger an image step by step requires a timer, which will be explained in the 11th lesson.

“do-while” Loop and “for” Loop

Similarly, “do-while” loop and “for” loop can be used to loop a block of code.  We can do the same thing with any of them, so use the loop you are most comfortable with.

The syntax of a “do-while” loop is as bellow.

  • do { process } while ( condition )

The process is executed once before checking the condition.  A “while” loop does not execute the code if the condition is false in the first place. Notice that a “do-while” loop executes the block of code at least once in any condition.


The syntax of a “for” loop is as written below.

  1. for ( variable initialization; condition; variable update ) { process }

An assignment for a variable is generally written at the initialization and update part.  The “for” loop is equivalent to the “while” loop below.

  1. initialization; while ( condition ) { process; afterthought; }

For details, look at the Reference below.

Exercise 09-9(☆☆☆☆)

Rewrite the program with for loop, for Exercise 09-7 and Exercise 09-8.

Points to check
  • What does x = x * 2 mean?
  • How is a while loop written?
  • What happens when the condition is already true at the beginning of a while loop.

No.8 Quantity of Information

The Quantity of Information

You may have used the phrase “the file size is too big”, or “the webpage is slow”, but information can be quantified precisely.

(PPT Download)

Exercise 08-1(☆☆☆)
  1. How many bits would be needed to distinguish blood types?
  2. How many trials would be needed to find out one’s blood type with yes/no questions?(for example:”Is the letter ‘A’ included in your blood-type? (yes/no)”-see the HTML below.  Draw an if statements diagram to answer this question.I would be more likely using the structure in the diagram for “Complex Comparisons” in the last chapter
  3. Create ex08-1.js, and write a function that shows a message “Your blood-type is ~” triggered by a click of the button.

  4. Add a function that check the input and then display an alert window “Enter yes or no”, when a word besides “yes” or “no” has been entered.

The Information Quantity in an Image

Information quantity in a bitmap image.. Revisit Exercise 04-0

  • A bitmap image consists of pixels.
  • A pixel in black-and-white photos,  as it is either black or white, holds one bit information (remember a bit can have a value of “1” or “0”). On the other hand, a pixel in colored photos requires the right amount of bits according to its color/information.
  • The information quantity of the entire image can be calculated by multiplying the number of bits in one pixel and the number of pixels.
Exercise 08-2(☆☆)
  1. How many kilo-bytes is a black-and-white photo with a resolution of 640×480?
  2. How many kilo-bytes is a 16-colored photo with a resolution of 640×480?

Text Encoding (Character code)

The process to convert readable letters into data, that can be processed by computers, is called text encoding.  <meta charset="utf-8"> ,that you have seen in the example HTML files throughout the exercises, specifies the text encoding for the HTML document. (FYI the opposite process is called “decoding”).

(PPT Download)

Exercise 08-3(☆)

Open a Japanese webpage (for example with Chrome and change the text encoding from View→Encoding. Change to for example Arabic and observe the outcome. (the video below is for japanese version of Firefox, not Chrome, but it does demonstrate the outcome).Remember the charset="utf-8" that you always have in your html? Having this in your HMTL means you tell the browser/Chrome which encoding you want Chrome to use. Now when you use the text Editor (Atom), you can also specify (when editing the file) which encoding you wish to use (by default it would be utf-8). The exercise below will demonstrate that there are 2 separate things that happens:

  1. Encoding process when the text was created and saved by Atom
  2. Decoding process that is done by Chrome, which will follow the directive written in html (the charset above)
  1. Create encodingtest.html with “Atom”. It should display ありがとう using heading1 tag. For the keyboard to switch from alphabet to Japanese (Hiragana in this case) Hold the Command key while pressing the spacebar until “Hiragana is selected”. Don’t forget to include charset="utf-8" as usual. Save it under
    your public_html/exercise as usual. Access it using your Chrome. Do the following things

    1. Change charset="utf-8" to charset="euc-jp", save the file and reload the page.What do you see? Change it back to “utf-8” and reload the page.
    2. On Atom, change the character encoding to Arabic(ISO 8859-6) (Edit-Select Encoding), save the file and view the file with Chrome.What do you see?
    3. Change charset="iso-8859-6" to charset="utf-8", save the file and reload the browser.What do you see? does the broswer display the same arabic charcter as displayed in Atom now?

if you somehow use Emacs editor (not Atom), it chooses a character encoding automatically when specified in charset, so the Exercise above will always show the proper contents.

Compressing Data

Raw data may have statistical redundancy that can be reduced.  In such a case, data compression algorithm can be performed in order to save memory by shrinking the data size.

(PPT Download)

Exercise 08-4(☆☆)
  1. Decode the following bit stream that has been compressed using Run-length encoding.
    • The length of each run (successive 0’s or 1’s) is 3 bits.
    • Start with the length of 0’s.
    • 000 represents that the same number is repeated many times.  For example, when 0 is repeated nine times, because 9 can’t be written with 3 bits, we must think of it as seven 0’s, zero 1’s, and two 0’s(111 000 010).
    111 000 110 001 111 000 001 001 101 111 100 011 101 001 011 001 011 001 101 001 001 001 111 001 111 000 010
  2. Make a grid of 9×9, fill in white for bits with 0 and black for bits with 1.  What shape came up?

In this exercise, the original data and compressed data are the same size.  Depending on the case, there may be times when the compressed data is larger than the original.

Exercise 08-5(☆☆☆☆☆)

Look at the Reference below and compress the following data with Huffman coding.

Tokyo Chiba Ibaraki Tokyo Kanagawa Gunma Tokyo Kanagawa Kanagawa Chiba Tokyo Chiba Saitama Tokyo Kanagawa Saitama Tokyo Tokyo Saitama Kanagawa Chiba Ibaraki Kanagawa Tokyo

Image Files

File Type

Image files have several formats that differ in number of colors, compression, etc.  The following formats are usually used on webpages.

Lossless compression. 8bit coloring(256colors).  Can be used for animation, by using multiple images.
Lossless compression.  48bit coloring(281,474,976,710,656 colors)
Lossy compression.The compression rate can be changed.  24bit coloring(16,777,216colors).

Photographs have different colors on every pixel and is difficult to compress it into a smaller size when using a lossless compression – which is the main reason of why JPEG is commonly used.  In contrast, lossless compression is used for illustrations and logos, as the same color is used for a certain area repetitively with a vivid outline.

Exercise 08-6(☆)
  1. Open your photo from your self introduction page using Preview.
  2. Click File→Save as…
  3. Select the lowest quality for JPEG and write it out as a different file.
  4. Open the preview of both, high and low, quality files. Can you see the difference?
  5. Compare the file size difference using Finder.

Size of Images

The size of an image sometimes means the file size, but usually the number of pixels. Actual size of the image (how many centimeters) cannot be determined because it depends on display devices.

As we learned above, the information quantity gets smaller as the number of pixels decrease.  If the compressed image file is still large, you can reduce the number of pixels (using coarse sampling) to get a smaller file.

When making a webpage with many image files, thumbnails are often used instead of original files, and the original is displayed when the thumbnail is clicked(to make the process faster).

Exercise 08-7(☆☆)
  1. Make a copy of your photo, and open the preview.
  2. Choose Tools→Adjust Size…
  3. Change the width and height, and confirm the file size.
  4. Edit the photo so the size is appropriate for a thumbnail.
  5. Edit Exercise 06-9 (save it as 08-7) so that it display the thumbnail image first but when the thumbnail image is clicked it will display the original photo.Tips: you can add an “onclick” event/attribute to an image tag so that the image become clickable. This onclick event would call a function that display the original image

You can add a onclick attribute instead of the button to improve the design.(Although users may not notice there is a function…)

Specifying the image size

In the img element, the size of the photo can be specified by manipulating width and height attributes.

  • The unit is in pixel.
  • If only one of the width or height attributes is specified, the other will be adjusted automatically to keep the ratio.

The setAttribute() can be used to change the size by scale.

  • Select the attribute with document.getElementById()
  • Add .setAttribute()
  • The arguments are the attribute name and the value you want to change.
Exercise 08-8(☆☆☆)
  1. Make a copy of your photo and name it picture.jpg.
  2. Create ex08-8.html and fill in the following.
  3. Change width="600" to width="400" and reload the browser.
  4. Make ex08-8.js and fill in the following.
  5. Create a button and call the function change() when the button is clicked.(Remember to add the script element to read the JavaScript file)
Exercise 08-9(☆☆☆☆)

Create a textbox, and add a function which changes the width of the image according to the number entered in the textbox.

The width and height attributes change the method of displaying a photo, but the original file size doesn’t change, so the time taken to display the webpage won’t change.

Points to Check
  • What is a bit?
  • How do we calculate the file size of a bitmap image.
  • What is a character encoding?
  • What is the difference between lossless and lossy compressions?
  • What kind of image is suitable for PNG and JPEG?

No.7 Conditional Statements

Inputting Data

Humans operate a computer by using a mouse or keyboard.  This is called “Input”. On the other hand, a computer communicates with humans by displaying texts and images, or making sounds from speakers.  This is called “Output”. We will learn about the relationship of the structure of computers and input/output on the 10th lesson.

Inputting Strings

Up to now, we have used mouse click as an input. Now, let’s try using the keyboard for input.  Make a textbox (as we learned on the 2nd lesson)、and JavaScript will be able to read the input.

Exercise 07-1(☆)
  1. Create ex07-1.html and fill in the following. Note that the text input element/tag is now “wrapped” with paragraph  tag (<p> tag). In this case it’s done so the text “Who?” can be displayed next to the text box.
  2. Create ex07-1.js and fill in the following.
  3. Type in your name in the textbox and click the button.

In order to read the value entered by the user, we use document.getElementById().value.  Note that it is different from document.getElementById().innerHTML, which we learned in the previous lesson. Also note that it is an event on the button (onclick) that calls the function to read the value. Do you remember “onchange” event (Exercise 05-13)? How would you use this for this case? You can eliminate the  need of having to click a button like the above for the purpose of reading a textbox! Read it here onchange event and text box

The content of the HTML element (tags excluded).”whatever in between the tags”
In case of textbox, it means the data input typed by the user. Other input elements such as buttons and checkboxes has value attributes but they are slightly different.
Exercise 07-2(☆☆☆)

In the exercise above, make another textbox that would allow you to enter a word so that the first word (“Hello”) can be changed to whatever the you have entered in that text box . For instance when “Yo” is entered in this textbox and “Taro” is entered in the “Who?” textbox, the result displayed when clicking the button should be “Yo, Taro!”. These 2 are Strings. Remember the operation to concatenate two Strings (Exercise 05-10) is “+”. The same operator (“+”) will add two Numbers.

Entering Numeric Values

Review Data Types (Lesson 5, point 5.4) to refresh your memory about the difference of String data type and Number data type.

As mentioned above anything entered in a text box is treated as a String, whether it is alphabetical (a,b,c..) , numerical (0,1,2), or anything else. This means  numbers entered in a textbox is handled as a String data type.  When we want to calculate these numbers, we must use Number() (which we learned in the 5th lesson) and convert them into Number data type before you can treat them as numbers.

Exercise 07-3(☆☆)Making a “simple calculator” to add two numbers
  1. Create ex07-3.html and fill in the following.
  2. Create ex07-3.js and fill in the following.
  3. Fill in a random number in the text box and click the calculate button. You will see that it is not working as expected as a calculator (to do the sum)
  4. Fix the program. The String needs to be converted to Number (Exercise 05-10)
Exercise 07-4(☆☆☆☆)

Make a program that calculates your BMI when you enter your height and weight.

if Statements and Conditional Expressions

How to write an if Statement

In general, programs are executed in order from the top  to the bottom , but there is a method to write multiple instructions and execute the ones that only matches in particular situations. This is called a conditional expression, and in JavaScript the “if statement” is used.

Exercise 07-5(☆)
  1. Create ex07-5.html and fill in the following.
  2. Create ex7-7-05.js and fill in the following (note that there are two equal marks next to each other, == instead of =).
  3. Type in the correct answer and click the button.  Try entering a wrong answer as well.

There are two constructs of if statement.

  1. Execute the command when the condition is true, and do nothing when false. The example for this is Exercise 07-5 above.
  2. Execute a command when the condition is true, and execute another when false.

The two constructs are:

  1. if ( condition ) { process }
  2. if ( condition ) { process1 } else { process2 }
Exercise 07-6(☆☆)

Edit the previous file so the message “Wrong!” appears when the answer is incorrect. This requires you to rewrite the program in #2 style above, assigning “process2” for displaying “Wrong”.

Specifying Conditions for If statement

All conditions specified in an If statement are evaluated to either “true” or “false”, as you can see in the flowchart/diagram above. There are ways to specify these conditions. For the purpose of specifying the Condition in an If statement, let’s review the followings:
Relational Operations, Complex Comparison, Logical Operator. They will be explained in the following sections. A valid Condition for If should be a statement that result in “true” or “false”. You will see what are these “true” and “false” when you do exercise below (executing/typing condition/statement in console).

Relational Operators

In a program, numerical equality and inequalities are handled as operators as well as + - * /.  In order to operate a  numerical equality and inequality, we use operators such as “<“, “!=” or ” ==”.

By writing a relational operators between two expressions, the program compares them and gives you the result. The result is a Boolean data type and it is either true or false. Example:

if ( x>3 ) { alert('bigger') }

Exercise 07-7(☆☆)
  1. Execute the following with console to find out how those operator works
    • var x=2
    • x==2
    • x==3
    • x!=2
    • x!=3
    • x<2
    • x<=2
    • x<=3
    • '2'==2
    • '2'===2
  2. Edit Exercise07-6 and change the conditional statement from “equal” (==) to “not equal”(!=), and replace “Correct” and “Wrong ” accordingly to keep the program works correctly.

The reason why we use two equal marks is because one single equal mark is the command that assigns a value to a variable. It will not get evaluated to true or false, hence not suitable to be used as a Condition in If statement. If you mistakenly enter only one equal mark inside the condition, no errors will occur but the program will most likely give you the wrong result.

Exercise 07-8(☆☆☆)
  1. Fix the change you made in No.2 of Exercise 07-7 back.
  2. Erase one equal mark inside the conditional statement.
  3. Type in a wrong answer in the textbox and solve the riddle.
  4. What happended and why?
  5. Fix the program back.

Complex Comparisons

Let’s make the answer newspapers correct as well (not only “newspaper”).

In order to do so, we must compare the input, “newspaper”, and “newspapers”.  However, a relational operator can only compare two values at once.  Let’s try comparing the three by combining two if statements, comparing it in 2 stages: compare it to “newspaper” first , then compare it to “newspapers” later. This means you need to have 2 conditionals. Let’s implement it below.

Exercise 07-9(☆☆☆)
  1. Draw the following image on a paper.  Write “If the input equals ‘newspaper’ ” for “Condition”, and write “display ‘correct’ “for “Process 1”.
  2. Now to check for “newspapers“-with s, you need to place another Condition check /Decision inside “Process 2”. Basically you would substitute Process 2 with another Decision/Condition check. It’s like having a whole flowchart above inside Process 2 (nested). For this second  Decision, what should you write inside Condition, and the 2 processes under the Condition? Check out this Flowchart as an illustration only for this case Sample flowchart (
  3. Edit the riddle program to match the diagram
    • It is troublesome having to write document.getElementById('answer').value each time, so you should assign a value to a variable first, and use the variable later, for example var theanswer=document.getElementById('answer').value
    • When the input does not match ‘newspaper’, another if statement should be used to compare the input and ‘newspapers’.

If there is only one statement inside the true/false part of an if statement, the { } can be taken off (actually, you can only write one statement, so we use { } to have two statements). It is however a good practice to always use { } even if you only have one statement.

Sometimes you see another single if statement that comes after an else. This is an  else if structure and the format is the as described below.

For this structure the condition1 is first checked. If condition1 is true then the process1 get executed. Else If condition1 is false then condition2 get checked.  If condition2 is true then process2 get executed. Else If condition2 is false the condition3 get checked and so on. If all the conditions are false then process_n (under else) get executed. Flow chart of the else if structure: (

    if (condition1) {
    } else if (condition2) {
    } else if (condition3) {
    } .....
    } else {
Exercise 07-10(☆☆☆☆)

Edit the program from Exercise  07-4 so that the following messages show up. Use the else if structure explained above.

  1. When the BMI is under 18.5, “Underweight
  2. When the BMI is over 25, “Overweight
  3. When the BMI is in between, “Normal
  • The first if statement should check the condition whether the BMI is under 18.5.
  • If the BMI is over 18.5, the second should check the condition whether its under 25.

Logical Operators

Another method when doing multiple comparison of values is using logical operators. The result is called “boolean” and it is either true or false. There are 3 basic logical operators: AND, OR, and NOT. Their “truth tables” are provided below.(source:

The following logical operators are used in JavaScript: && for AND, || for OR, ! for NOT. Examples:

  1. (x&&y) means (x AND y)
  2. (x || y) means (x OR y)
  3. !x means NOT x

x and y can represent Conditions for If statement. for example x is (a<5), y is (a>1), or for example x is (b==”newspaper”) y is (b==”newspapers)-just like in the exercise 07-9.


  1.  ( (a<5) && (a>1) ) . This is true for a with values of 2,3,4
  2. ( (b==”newspaper) || (b==”newspapers) ) This is true for a with value of “newspaper” and also true for b value of “newspapers”
  3. !(a<5). This is true for a values of 5,6,7,……
  4. ( (a>1) && (b<9) && (a!=5 ) ) . This is true for a with values of 2,3,4,6,7,8. Note here that there are 3 conditions!

Example of usage in if statement:

if ( (x>3)&&(x<10) ) { alert(‘size is OK’) }

Review the Reference below.

This method is based on logic. Logic is the basics of many subjects. For reference only , review these slides. (Download PPT)


Exercise 07-11(☆☆)

  1. Write a conditional expression of the following.
    • is larger than 1 and smaller than 10
    • is equal to either ‘newspaper’ or ‘newspapers’.
  2. Fix the riddle program so that only one if statement is used.

Exercise 07-12(☆☆☆☆☆)

Look at the Reference below and make a program that determines if it is a leap year or not by filling in a year in the textbox.

Points to Check
  • What is the difference between document.getElementById().innerHTML and document.getElementById().value?
  • What two methods are there when writing a if statement?
  • Which operator is used to determine whether two values are equal?
  • What data type is returned from a relational operator?
  • How can we compare three values at once?

No.6 Functions and Variables

Declaring Functions

In Lesson 5 we have seen JavaScript was written in the event handler on a HTML file.  In Exercise 05-10, the program/code (alert("Hello, world!");) was written inside the HTML file, thus a separate JavaScript file was not required.

However, as the program gets longer and longer it will be difficult to write all of the codes (many lines of codes) that way. Therefore, the program itself is usually written in a separate JavaScript file, and the event handler is used to call the program.

There are cases when one webpage uses multiple programs, therefore it is required to name each program.  A function is a bundle of program code/statements that can be called when needed. This way we can also give it a name.

Exercise 06-1(☆)
  1. Create  ex06-1.js and fill in the following.
  2. Create ex06-1.html in the same directory, fill in the following, copy them (HTML and JavaScript) to your public html as usual,  and access the html using the web browser.

Note that  this time “Hello, world!” did not pop out because it is not run/executed.  When a function { ... } is declared in the javascript , the  { ... } part is not executed, but it is only registered as a function so it can be called later on. In this Exercise, sayhello is the name of the function.  We will learn later why there are parenthesis written after the function name.

Registering a function like the exercise is called “declaring” a function.

Calling Functions

Once a function is declared, the program inside the function can be executed when we want by calling the function. It will be shown below.

Exercise 06-2(☆)
  1. Access the HTML file from the exercise 06-1 , open the console , type and run (pressing enter)  the following command on the console.
  2. Edit ex06-1.html and add the following inside the body element and reload the page. Note that here you are assigning/making this function as an event handler. The function will get executed/run when the “onclick” event happens (the button is being clicked)
  3. What happens when the line is changed to the following?

When we call a function, the program/code inside that function will be executed.

During the last lesson, we learned that we call the function Math.sqrt when calculating the square root of a number.  Math.sqrt and sayhello are both functions, but Math.sqrt is a function defined by the system (built-in function). sayhello is a function that you declared by yourself.


Exercise 06-3(☆☆☆)

Create a function saygoodbye, which shows the message “Goodbye.”, and create a button, which calls the function when it is clicked.


Variable Declaration

A variable is like a box that can contain data.  For instance, when we type innerHeight into the console, a number is displayed.  This is a variable used by the browser, which contains the value of the size of the window (technically the size of the content part).


We can make variables on our own. In order to do it, we execute the statement var variable_name;. This is called “declaring a variable”.

Exercise 06-4(☆)

Enter the following formulas in the web console and confirm the results.

  • x
  • var x;
  • x
  • When a name that hasn’t been declared as a variable or function is called, the Reference Error is returned.
  • When a variable that has no value is called, undefined is returned.(undefined is not an error)

Assigning a Value to a Variable

Saving data inside a variable is called assigning a value. We write variable = value; when assigning a value. If we want to declare a variable and its value together at once, we write var variable = value;.

Exercise 06-5(☆☆)
  1. Create ex06-5.js and fill in the following.
  2. Note the “+” sign inside the alert. It works exactly like it is for String data type (exercise 05-10)

  3. Create ex06-5.html and fill in the following.

  4. First of all, click on Greetings button.  Then click on Taro→Greetings→Hanako→Greetings.  What value is inside who and why?
  5. Edit ex06-5.js as the following and click in the same order as 3. Is there any difference?

These are the rules on where to declare variables.

  • A variable used by more than one function needs to be defined outside of the functions. (Generally written on the top of the JavaScript file). This is called a “global variable”
  • A variable used with only one function should be declared inside the function. This is called a “local variable”.
Exercise 06-6(☆☆☆☆)

When we click the button Taro and Hanako, there aren’t any actions /movements and you might be wondering.  Edit the file so that the message “Taro/Hanako has come” pops up when the button is clicked. Make a new function that displays “has come”, and call it from function taro() and hanako().

Function arguments

In the previous exercise, we made two different functions for taro and hanako. This wasn’t so difficult because there were only two people, but what if there were ten or hundreds?

An “argument” is used to process multiple data with one function.

  • When calling a function, the data or variable that we want to pass on is written inside the parentheses.
  • When declaring a function, we write a variable inside the parentheses. This variable will be assigned with the data used when the function is called.
Example 06-7(☆☆)
  1. Create ex06-7.js and fill in the following.
  2. Create ex06-7.html and fill in the following.
  3. What happens to variables x and who when Taro is clicked?
  4. Use function someone and make a button that greets “Rei”, “Shinji”, and “Asuka”.

When there are multiple arguments, each argument is separated by commas.

Manipulating HTML Elements using JavaScript (using innerHTML)

Unlike HMTL, which can display fixed/static text/information only, JavaScript can read and change what is displayed on the webpage by interacting (reading or changing/manipulating) with HTML elements. An HTML element can be accessed by JavaScript in 2 ways:

  1. reading it
  2. changing/manipulating it

In order to do it, we need to use the followings.

  • First,  in the HTML file, we mark the place (HTML element) which we want to access. There are a few ways to do it, but in this class we will be using theid attribute. This means we need to assign id attribute first to the HTML element that we want to read or change/manipulate using JavaScript.
  • Now that element has an id, we can refer to it  from JavaScript program by its id. We use the following statement (x is the id we assigned to the element):


For now, let’s look at the example where innerHTML is being used to read the “inner part” of an HTML tag (hence the name). The innerHTML basically refers to “whatever in between the tags”. Again as explained above we can use it in 2 ways:

  1. reading what (may already) exist in between the tags.
  2. changing/manipulating what (may already) exist between the tags. This will have an effect of, for example, changing/manipulating what is displayed on the web page, if it’s an HTML element that is related to displaying something on the page (text, image, etc).

For reading the format would be
z = document.getElementById(x).innerHTML

z will be assigned a value of whatever in between the tags of an HTML element with id=x

For changing/manipulating, the format would be document.getElementById(x).innerHTML = y

whatever in between the tag of an HTML element with id=x will be replaced by y

Note that z and y are String data type

Exercise 06-8(☆) Reading HTML element value using innerHTML
  1. Create ex06-8.js and fill in the following. Note that the JavaScript statements are referring to an HTML element with an id “who”.
  2. Create ex06-8.html and fill in the following. Which HTML element has id “who”? Its the paragraph <p> element! You can now see that the JavaScript above is”reading” a paragraph. In which way? It reads whatever in between the <p> and </p>. In this case its “world”. It then uses this value when displaying the alert/pop-up window
  • The id attribute and class attribute are similar, but in a HTML file, an id attribute with the same value cannot be used more than once.  In the case of the Exercise above, id=”who” is used in the p element, so in this HTML file, other elements cannot have the value id=”who”.
  • Elements with the id attribute can be accessed with JavaScript by using document.getElemetById().innerHTML.  This can be used like a variable (when reading), and when a new value is assigned (changing/manipulating) the display on the browser will change accordingly as well.

documentgetElementById() and innerHTML have the following meaning.

  • document : The source of the page displayed
  • getElementById() : A function which finds the specified ID(an HTML elements with a specified id)
  • innerHTML : The content with tags excluded.(“whatever in between the tags”)

Note that the 3 “keywords” above are joined together with a period/dot. In order to understand the meaning of the period, we must study “Objects”, but we will not go so far in this class.

Exercise 06-9(☆☆☆)Changing/manipulating HTML element value using innerHTML
  1. Take a picture of yourself with a different expression from the self introduction page using PhotoBooth, and save it in the same directory as the previous photo.
  2. Edit the img element on your self introduction page as the following: <div id="..."><img ...></div>
    • div element doesn’t have any functions by itself, but is used to add id and class attributes.
  3. Create ex06-9.js, and make a function that change/manipulate the content of the div element, to change the img element from the first photo to the second photo.
  4. Don’t forget to create  a <script> element/tag inside the <head> element which reads the JavaScript file we just made (ex06-9.js)
  5. Make a button (button #1, above or below the photo) that corresponds with the function that you made. (The onclick event on the button need to call that function)
  6. Open the file via browser and confirm that the photo changes when you click the button.
  7. Make another button(button #2) that returns the photo back to the original.

This is how it works: When you access the HTML by the web browser, the HTML gets loaded into the computer/web browser’s memory. The JavaScript change the HTML element inside the memory, but *not* the HTML file it self! (yes you can change the displayed photo by changing the HTML, save it and reload the HTML again as well, but this is static, not dynamic. With JavaScript above you can change the displayed photo by clicking a button!

Try opening a web page, then open Google Chrome’s Developer Tools (View-Developer-Developer Tools), “Elements” tab. Try changing some elements, you will see the result will be reflected straight away. This is because you are changing the memory content , *not* the html source file itself!

Executing a Function with a Timer Event

By using a Timer event, we can execute functions after a certain period of time or evert a certain period.

Exercise 06-10(☆)
  • Execute the following command via console.

The setTimeout function has the following two arguments

  • A string that contains a program you want to execute.
  • How many milliseconds (1 second is 1000 milliseconds) before it gets executed.

Double quotes are used in the Exercise above to distinguish them from the single quotes outside alert().

Exercise 06-11(☆☆☆☆☆)

Modify Exercise 06-9 so that the photo automatically switch back 5 seconds after you click the button #1. Keep button #2

Points to check
  • What is a function?
  • How do you declare a function?
  • What is a variable?
  • How do you declare a variable?
  • How do you assign a value to a variable?
  • What happens when you use arguments?
  • What is the id attribute used for?

No.5 Script


In a web page, we learned that HTML is used to define the structure, and we can add pictures or CSS.

However, with only HTML and CSS, the web page is pretty much static For example the text that you specify with the “paragraph” <p> tags will remain unchanged.You can’t really add “movement” to the page. This also means that the page is not really interactive with users.

To create an interactive  and dynamic webpage, we need to write a program.  One of the most popular programming language used for web page is JavaScript.

JavaScript and Java is a different language.  Be careful when buying a book of reference. Make sure to choose the book on “JavaScript”.

”Program” and “Script” basically means the same.  Short programs are usually referred to as scripts.

JavaScript can as well be written in a separate file like CSS.  To avoid confusion, in this class we will write the JavaScript program in a separate file to HTML.

The way you access your exercise should be using your web browser , through URL, for example: , NOT through file:// (it means do not open your HTML by either right clicking and opening using Chrome or using File-Open File through Chrome’s menu

Exercise 05-1(☆)
  1. Create ex05-1.js and write the following.

  2. Create “ex05-1.html" in the same directory and write the following.

  3. Store the both files (html and js) under your exercise directory , access  ex05-1.html via browser(through URL) and see what happens. Note that line #7 is the one that “links” your html to your JavaScript. Without this the JavaScript will not get executed by the browser (a JavaScript , in a browser, always gets loaded by an HTML)
  4. Edit ex05-1.js and change “world” to your name.
  5. Edit ex05-1.js and type in the same sentence.
  6. Change “Hello” in the second line to “Goodbye”.

Hello world is a traditional program that beginners make.

Executing a Program


JavaScript is a language that instructs browsers to execute commands. For instance, alert is a command that displays a text inside a dialog box. JavaScript is executed by the browser and within the browser environment. Any mistakes therefore will be contained within the browser and will be very unlikely to affect your computer. You should not therefore by too worried in creating and running JavaScript in these exercises!

Browsers displays the content on HTML in order (top to bottom) but it executes programs when it recognizes a  script element. When there are multiple commands, they normally will be executed in order.

Exercise 05-2(☆☆)
  • Edit ex05-1.html and write the following.  What have changed?
  • You will see and experience later on that the location of the <script> tag could affect the behaviour of your program/web page, because as mentioned above the browser interpret the lines in order, from top to the bottom, in general.

How to use Scratchpad (only for Firefox web browser -not available as a built-in feature in Chrome-need to install an “extension”)

There are times when we want to try changing a small part of a program and see what happens, but starting up a browser each time is quite irritating.  In such a case, you can use scratchpad on Firefox to directly change and execute the program.

Exercise 05-3(☆)
  1. Select Tools→WebDeveloper→Scratchpad,
  2. Type in alert('Hello, world!');
  3. Execute the program by selecting Execute→ Run and see what happens.

How to use Console

When there are errors in a program, the program would (obviously) not run. However, If there are no clues, it would take a tremendous amount of time to find the error. Therefore, browsers have a function that gives us error messages.

Exercise 05-4(☆)
  1. For Firefox: Select Tool→Web Developer→Web Console , For Chrome: Select View-Developer-JavaScript Console
  2. Edit ex05-1.js and change alert to alart.
  3. Reload the browser and check the console.
  4. Fix ex05-1.js, reload the page and re-check the console.

Basic Syntax

We will study JavaScript from now on, and here are some basic rules to remember.

  • Always remember to close parentheses.
  • Enclose string literals(text used as data, the “hello world!”) with single or double quotations.
  • Spaces and new lines can be set anywhere(except the middle of a word).
  • Comments are enclosed with /*  */ .  // can be used to comment out the text behind, on the same line.
  • Non-English characters can only be used in string literals and comments, and other parts of the code must be written with ASCII characters (ASCII will be covered in the 8th lesson).
  • Make a habit to close statements(the smallest unit of a program that can be executed) with a semi-colon.  There are cases when you don’t need to do it, but it is a good practice and preferable for preventing any trouble.
Exercise 05-5(☆☆☆)
  1. Open the following JavaScript files via browser(Chrome) and save the file (File→Save Page As…)
  2. Create a HTML file that reads these JavaScript files. As usual store those file under exercise directory , under your public_html
  3. Access the HTML file and check the errors on the console.
  4. Fix the errors.

We went through the practice of saving the JavaScript file, making a HTML file that reads these files, and starting up a browser… , but if all you want to do is search for errors, you can simply use scratchpad.

Calculating a Formula

Easy Formulas

We can write formulas inside alert instead of texts, and the result will be displayed.

The basic arithmetic operations can be written as you would normally do in math.

Exercise 05-6(☆)
  • Edit ex05-1.js and write the following. Access the file via browser.

Calculations using Functions

To calculate more complicated formulas, we use functions.  For instance, when we want to calculate the square root of a number, there is a function called Math.sqrt. This along with many other functions are “built-in” functions that comes with JavaScript. Later on Lesson 6 you will learn how to make your own function.

Exercise 05-7(☆)
  • Edit ex05-1.js and write the following. Open the file via browser.

alert(Math.sqrt(1+1)) , alert(Math.sqrt(2)) , and alert(1.4142135623730951) is the same meaning.

When a function is used to calculate a formula, we call this “calling out a function”.  When a result is given from a function, we call this “returning a value”.  For instance, when we “call out the function” Math.sqrt(2), the value 1.4142135623730951 “is returned”.

Calculating via Console

It is annoying to edit the Javascript file each time we want to evaluate an equation. Instead, we can click on the bottom line of the console, type in the function, so that the result will be displayed.

Exercise 05-8(☆)

Execute the following functions via console.

  • 1+1
  • Math.sqrt(1+1)
  • alert(Math.sqrt(1+1))

alert is also a type of function.  It is not used to calculate a value, but is used to display an alert box. This function returns a special value undefined (this function does not really return a value).

Exercise 05-9(☆☆)
  1. Calculate the sum of square root of 2 and 3.
  2. What happens when you divide 1 with 0?
  3. What happens when you divide 0 with 0?
  • Infinity means that the result is a number larger than what JavaScript can handle.
  • NaN stands for “Not A Number”.  This means that the result cannot be displayed as a numeral value.

Data Type

There are various types of data that can be used with JavaScript, and we call this “data type”.  Basically you need to know at least 2 data types: Number and String. A numbers or letters are data types.  Different methods are used to calculate each data type.  When calculating different data types with each other, the browser automatically converts them or returns errors.

  • For example 12 is a number, but it is a string literal made of the letter 1 and 2.
  • + is the symbol meaning add, but when used with the data type string, it can be used to connect string literals.
  • The Number function converts string literals to numeric values.
Exercise 05-10(☆)

To understand the difference between data type Number and String (VERY IMPORTANT!), Execute the following functions via console.

  • 2+3
  • '2'+'3'
  • Number('2')+Number('3')
  • '2'+3
  • Number('2')+3
  • ‘A’+’b’

Execution by Events

The program “Hello world” is executed when the browser reads the page, and after the alert box shows up, there is no movement.  This is a little boring, so let’s make a program that corresponds with the users actions.

The trigger for executing a command is called an “Event”.  There are many types of events, and if there is a program that you want to execute when there is  an event, you must define the “event handler” that corresponds with HTML elements.

Exercise 05-11(☆☆)
  1. Create the file ex05-11.html and fill in the following.
  2. Make a copy of the input element and edit onclick to ondblclick. Change “hello world” to text of your choice.  Reload the browser and try clicking or double clicking the button.

In this case, onclick and ondblclick are the event types, and the part enclosed with quotations is the event handler.  A JavaScript program is written inside the event handler. So this is the order: an event defined in HTML will call an event hander (in this case  a function) in JavaScript. This is another link/interaction between the html and the JavaScript that you need to understand. Notes: Later in lesson 6 you will also see that JavaScript makes a reference to elements in HTML! (for example using getElementById). This will be covered later.

onclick is generally used for events associated with buttons. It will however works with other elements  too as long as the event handler is correct.

Exercise 05-12(☆☆☆)

Edit the header (Heading 1/<h1>) “Practicing Event Handlers” so that “Hello, world!” shows up when you click it.

Even if the onclick event handler is set to headers or paragraph,
visitors cannot see it. You should tell them “click here” by changing color or underlining it (use <u> tag).

Exercise 05-13(☆☆☆☆☆)

Look at the Reference below, and make events that shows messages when moving the cursor or changing the text inside a textbox, etc…(you need to find out which events that are associated with cursor movement and changes of input in a text box). Hints: for cursor movement find it under Mouse Events, for changes of input in a text box find it under Form Events)


Points to Check
  • What is a program used for?
  • In what order are the statements inside a program executed?
  • What does “calling out a function” mean?
  • What does “returning a value” mean?
  • What is an Event?
  • What is an Event Handler?

No.4 Images and Style Sheets

Files that Construct a Webpage

Up to the previous lesson, we learned that HTML files correspond with webpages. However, there is a limit to what you can do with HTML, and it is common to combine HTML with other types of files.

The following files are often used.

Style Sheet(CSS)
Used to define the visual layout (font size, colour and etc) of a webpage.
Used to process data or to add movement to webpages.
Images(JPEG, PNG, etc)
Pictures displayed on webpages.


In this lesson, we will learn about style sheets and images.  We will learn about scripting on subsequent lessons.


Analog and Digital

Computers used nowadays mainly process digital data.

(PPT Download)

Exercise 04-0(☆☆)

Download this image (click or right click-Save Link As)
Inspect its properties using “Finder”.
What is the “colour system” used by this image?(How many possible colours?). Tips: Examine the file size of this image (how many bytes?). Examine the dimension of this image (how many pixels: for example 300 pixels X 500 pixels). For now just keep in mind that 1 byte can represent 256 colours(we will cover this in detail in Chapter 8, and will also be covered below on the slide “Binary and Hexadecimal Numbers” )

Exercise 04-1(☆☆)

A few years ago, the analogue broadcasting finished in Japan. Why did the broadcasting method of television change from analogue broadcasting to digital broadcasting?

Displaying a Image File

Let’s take a photo of yourself and display it on your self introduction page.

Exercise 04-2(☆☆)
  1. Start up Photo Booth from the application folder.
  2. Photo Booth is an app that takes pictures with the built-in camera on iMac.  The button with the camera mark is the shutter, and you can add effects to the photo by clicking on the “effect” button.

  3. Save the photo from File→Export.
    • Using white spaces or Japanese characters in a file name may result in complicated issues, so make sure to use only alphanumeric letters.
  4. Open the file by double-clicking it.  “Preview” should start up.
  5. Trim the photo by selecting the range you want(with your mouse), and select Tools→Crop.
  6. Use “Tools→Adjust size…” in the menu so that each side of the image is within 200~300 pixels.
  7. Save the edited photo to a file.
  8. Check how to use the “img element” in the Reference, and display the photo on your self introduction page.
    • Use relative URL to specify the file.  It is easier to have the HTML file and image file in the same directory.
  9. Use the “title attribute” and add a description of the image.
  10. In this case, how should we specify the “alt attribute“?

Due to privacy issues, some people say that you shouldn’t upload mug shots.  The file we made today can’t be viewed from the web, but be careful when uploading personal information to the internet.

Exercise 04-3(☆)
  1. Add “Keio University” to the list of schools on your self introduction page, and display the SFC logo mark.
  2. Attach the “<a> element” and link the image to SFC’s Homepage.
  3. In this case, how should we specify the “alt attribute“?

Image files have copyrights. When using an image file from the web, we must follow the rules of citation or get the permission from the author.

Like image files, we can make and display videos on the web as well.  However, there are many formats when using a video, and depending on the browser, some formats will not work.

Style Sheet

What is CSS?

Explained on the 2nd lesson, HTML is a markup language that describes the structure of a webpage.  CSS is a language that describes the design of a webpage.

There are a few levels defined in CSS.  Recent browsers support Level3(CSS3), but depending on the browser, there might be functions that won’t work.  When writing a CSS file, remember to check whether each function will work or not on your browser.

CSS is written in a separate file from HTML, so we must define (on the HTML file) which CSS file to use. First of all, browsers load HTML files and then load CSS files, and finally display them on the screen. It is same to the case of img element, when the specific image file is loaded and then displayed.

There is a method to write CSS inside HTML, but in order to avoid the confusion, we will use how to write on separate files in this class.

Syntax of CSS

In a CSS file, we line up the definition of style. It has a form of “where” and “what” style you want to do.

A “selector” is used to declare where to apply each style on HTML.  There are a few ways to define the selector, and the easiest way is to write the element of the HTML.  For instance, when we want to set the style of the header, we can simply write h1.  When specifying multiple elements you must separate each selector with a comma.
The “property” is defined like the following: aaa is bbb.  For instance, the property color : blue indicates that the color is blue.  When there are multiple properties, you must separate each property with a semi-colon.

A style is written like the following: selector {aaa : bbb}

Spaces and new lines can be placed freely (but not in the middle of property). Comments can be written by enclosing a text with /* and */.

Exercise 04-4(☆)
  1. Make the file mystyle.css (via text editor) under the same directory as your self introduction page, and write the following.
  2. Open introduction.html and add a link element to the head element.
  3. Open your self introduction page via browser and check out what is it changed. If nothing happened, make sure the header is written with a h1 element.
  4. Edit mystyle.css, change blue to green and reload the page.

Defining the Color

The color you specify in CSS can be written by simply typing in the name of the color(such as blue and green), but when we want to use colors that aren’t defined in CSS, we need to type in the color code.  Color codes use hexadecimal numbers, so let’s take the time to study binary and hexadecimal numbers first.

(PPT Download)

Described in Analog and Digital, we must quantitize the color into numeric values.

  1. Break up/decompose the primary colors of light into red(R), green(G), blue(B).
  2. Set the brightness of each color in the values between 0-255.
  3. Convert each of these values into two digits of hexadecimal numbers(00-FF).
  4. There is a method to write 3 hexadecimal numbers in the order of RGB, however we will make one hexadecimal number with six digits(000000-FFFFFF).

This number can be used as a color code by placing a # before the first digit.

Exercise 04-5(☆)
  1. Open mystyle.css, change the color code to #F0A050, and reload the browser.
  2. Edit the numbers of the color code and see what kind of colors will be displayed.

Defining Borders

The class schedule does not look smart without borders, so let’s add some.

Exercise 04-6(☆)
  1. Add the following style to mystyle.css and reload the browser.
  2. Check out the Reference of border property and set a border of your choice.

“class” Attribute and Selectors

Same style for each element will be applied, if we define the selector with the element name.  Instead, if we want to apply different styles (within the same element), we can define the “class attribute” to classify each element. From now on, we will simply call the value of the class attribute class.

The selector of a style using class is written like the following: element.class

Exercise 04-7(☆☆)
  1. Choose 2 or 3 classes that you think are most important on your timetable, and set the class of td element to important.
  2. Add the following style to mystyle.css and reload the browser.
  3. Choose classes that aren’t that important (Of course it doesn’t mean you can fail these classes 🙂 ) and display the letters in blue.

You can omit the name of the element and simply write .class to set the style for each class without applying the element.

Exercise 04-8(☆☆)
  1. From the list of your hobbies, select one of them and make the class name important.  What color is displayed?
  2. Edit mystyle.css so that it displays class important in red on both the timetable and hobby.
Exercise 04-9(☆☆☆☆☆)

There are times when styles conflict with each other.  For instance, when we want to use blue for element td and red for class important, what color will be displayed in <td class="important">...</td> ?  First, try it by yourself, then study about the priorities of selectors, explained on Reference below.

Using Firefox Inspector for CSS-(Reference only.Chrome, below ,(section 3.7) , is recommended for this class)

We learned how to use Inspector for HTML , let’s try using it for CSS.

When searching an element, the CSS pane is displayed on the right side.  There are 4 kinds of displays and can be switched by clicking on the tabs.

Lists all the rules that apply to the selected element.
Lists all CSS properties and their final processed values.

On the Rules display, rules can be switched on and off by clicking the property.  You can change the value of the property as well.  Try changing some values.

Using Chrome Developer Tools for CSS-recommended

We learned how to use  Chrome Developer Tools (2.6 at Lesson 2), let’s try using it for CSS.

When searching an element, the CSS pane is displayed on the right side.  There are 5 kinds of displays and can be switched by clicking on the tabs, 2 of them are:

Lists all the rules that apply to the selected element.
Lists all CSS properties and their final processed values.

On the Styles display, rules can be switched on and off by clicking the property.  You can change the value of the property as well.  Try changing some value

The videos below are for Firefox (Inspector) only. No video is available for Chrome Developer Tool yet (please ask SA or Lecturer for assistance when required)



Exercise 04-10(☆☆)
  1. Open your self introduction page and display the information of the header(h1) using Chrome Developer Tools (“Elements” tab) .
  2. Click on the color property and switch it on and off.
  3. You can add properties by clicking the blank areas.  Add the font-size property and change the value to 48pt.
  4. Change the font-size property to a size of your choice.

Web Accessibility

HTML describes the structure of the webpage semantically, and a style sheet is used to apply the design to the page.  The reason for dividing these roles is based on the thought that the most important duty of the web is to provide information to millions of people, and to do so, the method of how to display the information can vary depending on the recipient.

Web accessibility refers to the practice of removing obstacles for people with disabilities, from accessing the web. In web accessibility, it is important to write separately the structure and appearance.

Exercise 04-11(☆☆☆☆☆)

There is a web accessability checker that inspect whether the page has a consideration of web accessibility. Try using it, by looking at the references below.

Points to Check
  • What kinds of files construct a webpage?
  • What are some positive points of converting analogue data to digital data?
  • What steps do you need to take to convert analogue data to digital data?
  • What is the difference between bitmap images and vector images?
  • What is the role of style sheets?
  • How do you define a style with CSS?
  • What is the class attribute used for CSS?
  • What is the web accessibility?

No.3 How the Web Works

File System

Before learning  how to write the “path” of a URL (an example of a url is , we need to  learn how a computer manages files.  A file system on a computer controls how to store and retrieve data from a disk.

Exercise 03-0(☆)

“Treasure hunting game”, refer to page 32 of the slides below

(Download PPT)

Making the file Accessible from the Internet

The pages we have made in class were only visible by yourself.  Depending on the privilege, some people might be able to access to the file but even that is restricted to people logged in on CNS.

Let’s try making the file accessible through the internet from all over the world. We will learn about its mechanism in Fundamentals of Information Technology 2.

On SFC-CNS, we can make a file accessible by placing it in a particular directory.

  • The absolute path of the directory is /home/(login ID)/public_html.
  • On the iMac, it can be found under Desktop→CNS_HOMEDIR→public_html.

When accessing the file from a browser, the address is ID)/(filename)

Exercise 03-1(☆☆)
  1. Make ex03-1.html and fill in the following.

  2. Change “foo bar” to a word that you like.
  3. Move this file under public_html.
  4. Access ID)/ex03-1.html via a browser.
  5. Access your neighbour’s page.

The access authorisation of a file must be set when making a file.  Files made by an editor on CNS will be set so that it can be accessed by anyone.  But in some cases, such as files that have been transferred or compressed, the access authorisation may be changed to another set so that only you can access it.  We will learn about the details of access authorisation on the 10th lesson.

When making a directory under public_html, the URL path will be the same as the relative path from public_html. For instance, if you were to make a directory hobby under public_html, and place a file music.html under hobby, the URL should be ID)/hobby/music.html


Exercise 03-2(☆☆)
  1. Make a directory info1 under public_html.
  2. Place ex03-1.html inside info1.
  3. Did the URL of ex03-1.html change?  Try accessing the file with a browser.  Try accessing your neighbour’s as well.

When publishing a webpage, you (of course) must obey copyrights and other laws, but you must also be careful about the by laws of SFC-CNS, which prohibits you from actions that may hurt the honour of Keio University.



HTML stands for HyperText Markup Language, but, what is Hypertext?  Hypertext is a text that contains links(hyperlinks) and can jump to other linked texts.

Exercise 03-3(☆☆☆)
  1. See how to write hyperlinks from the Reference.
  2. Search and link the homepage of your elementary, junior high, and high school to the self introduction page you made on Exercise 02-4.
    • If the homepage does not exist, add Keio University to the list and link SFC’s homepage.

Are there any problems to link pages without authorisation?  According to the Copyright Law, it is interpreted that there are no problems, but if there are any specifications you should morally respect them.

Specifying an URL

URL stands for Uniform Resource Locator and it is like an address of a webpage.  For example, the URL of SFC’s homepage is

A normal URL looks like the following.


  • The “scheme”(protocol) specifies how a browser should fetch the source.  Normal webpages use “http:“, but in the case of fetching an encrypted page(like net banking) we use “https:“.  When opening a file, we use “file:“, which means that the browser will fetch the file without connecting to the internet.
  • The host is the name of each computer, and specifies in which computer should receive the source from.  If the scheme is “file:”, then the host is always local so there is no need to write the host.
  • The path specifies which file in the computer is supposed to be fetched.

We will learn about in details about scheme in Fundamentals of Information Technology 2.

Absolute URL and Relative URL

Because an URL is like an address, we can specify the one webpage from pages all over the world, but inevitably the address itself gets longer and longer.  When specifying a house in the neighbourhood, we can say, “two houses next door from my house”, instead of “… Shonandai, Fujisawa-shi, Kanagawa”.  The same goes for URL, and there are ways to access a webpage without typing in the full address.

Exercise 03-4(☆☆)
  1. Access
  2. Display the source of the page by using Chrome’s  Source Viewer, and see how “Students who entered 2014 or after” is linked.
  3. Click on “Students who entered 2014 or after” and examine the URL. is an “absolute url” which can be accessed from anywhere, and new.html is a “relative url” which can only be accessed when linked from

Positive Points about an Absolute URL
It can specify any webpage in the world.
The same URL can be used to be linked from any other pages.
Positive Points about a Relative URL
It is shorter than an absolute URL.
As long as the relationship between each file doesn’t change, even if the website itself is relocated, there is no need to relink each file.

Note that the format of the relative URL is consistent with the directory structure, which you have studied in  “File System” part above.

You can access from or too, but this happens because you are relocated from a different page, and the actual URL is 

 Relationship of File system and URL

  • When the protocol is file:,  the absolute URL is file:// followed by the absolute path. For example, the absolute URL of /xxx/yyy.html is file:///xxx/yyy.html.  Because there is no host name, remember to write three slashes after file:.
  • When the protocol is http:, the absolute URL of a file depends on the setting of the web server.  On a general web server, relative paths under a certain directory are used. The case of SFC-SFS will be explained later.
  • With a relative URL, there is no need to type the protocol nor the host name.  The relative path of the file system itself is the relative URL.
Exercise 03-5(☆☆☆)
  1. Make a file link.html in the same directory as introduction.html(Exercise 02-4).
  2. Inside the body element, make a link to your self introduction page using a relative path.
  3. Open link.html via browser, click on the link, and confirm that you can jump to your self introduction page.
  4. Make a new directory dirA under the directory we have been working with.
  5. Move link.html under dirA.
  6. Edit link.html so that it to correctly jumps.
  7. Make a new directory dirB in the same directory as dirA and your self introduction page.
  8. Move your self introduction page under dirB.
  9. Edit link.html so that it correctly jumps.
Exercise 03-6(☆☆☆☆)
  1. Let’s make a web version of the “treasure hunting game” introduced on the slides (‘File System” section above).  The plan is to make a file map.html under each directory and connect them with hyperlinks.
  2. Let’s move the treasure hunting game to your own directory.  Enter the following command on Terminal.

    • mkdir is a command to create a new directory.
    • The /home//public_html/ is the special directory for publishing on the internet.  .
    • cp is a command which copies files or directories.  For the arguments, we write Copy From and Copy To.
    • -R is an option which specifies to copy every file in the directory.
  3. Confirm that there is islands inside the info1 directory.
  4.  Make a file map.html (with  content below) inside the directory islands 

  5. Make another map.html file inside island-a (which is inside “islands”) , and fill in the following.
    • A header “Map of Avalon”.
    • A link that jumps back to starting point(map.html inside the directory islands).
  6. Make another file map.html inside islandsisland-aport-a, and fill in the following
    • A link to file empty, which shows the text that depicts a  “Treasure Box”.
    • A link returning to “Map of Avalon”.
  7. Make pages for other islands and ports in the same way explained above. Try to make a shortcut from one port to another port in another island.

Files empty and garbage are not HTML file, and they run in different ways depending on the browser.  Firefox will show the containing text, and Safari will open the file with Finder.


You must always keep in mind of copyrights when exposing a webpage.

(Download PPT)

Exercise 03-7(☆)(Optional)

We are sorry that the video is only available in Japanese (licence related).

If you understand Japanese, “情報倫理デジタルビデオ小品集3” can be played on the iMac(Desktop→→ Watch the following parts and summarise the content.

If you understand Japanese, “情報倫理デジタルビデオ小品集3” can be played on the iMac(Desktop→Share_zmacindex.html).  Watch the following parts and summarise the content.

  • 12. アップしたビデオが著作権侵害!
  • 27. Web貼りつけレポートはNG
  • 29. ブログでメール紹介したらダメ?
  • 30. Webカメラは肖像権を侵害?

(Due to license issues, the video can only be played on the iMacs in the Computer Room.)

Compulsory: (Watch in your own time) An English Video with similar contents is available here Information Ethics in the Digital Age

Exercise 03-8(☆☆)

There are webpages that offer free pictures, BGM’s, illustration and etc. for creating a webpage.  Search those sites and read the Terms of Use.

There are free sites that contain virus or spyware. It is important to keep in mind not to download from suspicious websites, and always operate the security software with the latest version.

Points to Check
  • What is the difference between a HyperText and a normal text?
  • What is the difference between an absolute URL and relative URL?
  • Why is the structure of files and directories called “Tree Structure”?
  • What does “..” represent in a relative path?
  • Which directory on SFC-CNS is published on the internet?
  • What kind of rules are there in Copyright Law?
  • Are there any exceptions in Copyright Law?