# No.11 Array

## Array

### What is array?

When we have many data of the same kind, it is more convenient to number them than to name them. Using array, we can store multiple data (called elements of the array) inside a single variable. To specify one of the data, we use a number to index the elements.

Exercise 11-1（☆）

Execute the following with console.

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

Brackets `[ ]` are used in the following two manners.

• To specify an array as a whole, a list of data is written in the bracket, punctuating with commas. In the first line of the example above, we create an array which consists of three strings `'Alice', 'Bob', and 'Carol'`.
• To specify an element of an array, we use an expression like `x[0]` where a variable `x` should store an array and a number 0 in the bracket is an index of the element. Note that the index of the first element is 0. Threfore, `x[0]` refers to `'Alice'`.

Assignments also have two forms.

• In the first line of the example above, the entire array is stored into a variable `x`. In this case, the left-hand side of the equal is a variable name without an index.
• In the fifth line of the example above, `x[2] = 'Charlie'` means to replace `'Carol'` (an element of index 2) with `'Charlie'`. In this case, the left-hand side of the equal includes an index because it refers a single element specified by the index.

## Iteration and Array

Arrays are useful because a lot of data can be processed in turn, by storing the index into a variable and changing its value with a loop.

Let’s make a calendar as an example. We can get dates easily incrementing one by one, but days of the week are difficult because they are different strings. So, an array is used to store strings “Sun”, “Mon”, “Tue”, … so that we can use a nubmer 0, 1, 2, … instead of the strings.

Exercise 11-2（☆☆☆）
1. In the same way as Exercise 09-5, we will create items (`li` elements) “Date 1”, “Date 2”, “Date 3”, … in a list (`ul` elements). Make `ex11-2.html` and `ex11-2.js` and fill in the following.

2. Which part of the program above corresponds to which part of the diagram below? How the value of the variable `x` will change as the loop repeats?
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. Rewrite `ex11-2.js` so that “Date 1 (Mon)”, “Date 2 (Tue)”, “Date 3 (Wed)” is shown. What happens after “Date 7”?
5. To get a correct display after “Date 7”, we may write 31 elements of `'Sun', 'Mon', 'Tue', ...` in the array, but there is a smarter method. 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.

Let’s make the calendar more practical.

Exercise 11-3（☆☆☆☆☆）
1. Create a new text field for “What month”. According to the number in it, 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. (There is a sample, but only Japanese version is available, and some of its functions are beyond the scope of this course…)

## Manipulating Multiple HTML Elements

`document.getElementById()` is used for specifying a 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 has a unique name in one page.

In contrast, `document.getElementsByTagName()` refers to multiple HTML elements, where a tag name should be specified in the parentheses. Since there may be a lot of elements of the same tag name in one page, `document.getElementsByTagName()` refers 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 with console. Do you see the corresponding parts in the page?
• `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` with console where `length` is an operation to get the number of elements in the array.
5. Open scratchpad, and execute the following 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 buttons are used for an input where we choose one among several alternatives.

• To create a radio button, write an `input` element with an attribute `type="radio"`.
• Write a different `input` element for each alternative.
• We need to specify which `input` elements make a group in which we can choose one. So, elements with tha same value for the `name` attribute make a group. For example, suppose we have alternatives ‘Policy Management’, ‘Environment and Information Studies’, ‘1st’, ‘2nd’, ‘3rd’ and ‘4th’, then we will give some value for the `name` attribute of ‘Policy Management’ and ‘Environment and Information Studies’, and another value for the `name` attribute of ‘1st’, ‘2nd’, ‘3rd’ and ‘4th’.

In a JavaScript program, in order to find which radio button is chosen, we first need to get radio buttons in the page. `getElementByID` can get only one button, and `getElementsByTagName` will get other `input` elements in addition to radio buttons. `getElementsByName` (where a value of the `name` attribute is specified in the parentheses) is used to get radio buttons in some group.

Exercise 11-5（☆☆☆）
1. Make `ex11-5.html` and fill in the following.
2. Display the file with a browser, and exexute the following with 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 is chosen or not. First execute `x[0].checked` with console when no buttons are chosen, and then execute it again after choosing ‘Policy Management’ in the page.
4. `true` or `false` can be used in `if` statement. First execute the following with console after choosing ‘Policy Management’ in the page, 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. Make `ex11-5.js` and fill in the following. Choose ‘Environment and Information Studies’ and click the button ‘Click here’. Explain the operation of the program.
6. Rewrite the program so that the grade is displayed as well as the faculty.
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 with a motor, and a rice cooker heats up rice with a heater.  How does a computer move?

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

Exercise 10-1（☆）
1. What is input, output, and processed in a vending machine.
2. On Exercise07-5, what is the input, output, and processed.
Exercise 10-2（☆☆☆）
1. On Exercise 09-5, `ex09-5.html` and `ex09-5.js` are saved on secondary memory, but what is saved on primary memory?
2. When the “pocket” button is clicked, another “Inside the pocket, there’s two cookie” shows up. 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 kind of data is exchanged between the primary and secondary memories?
Exercise 10-3（☆）
1. Start up the Activity Moniter(Appications→Utilities).
2. The usage of the CPU is displayed under the “CPU” tab.  Open some apps and see what happens.
3. Check the disk activity monitor.  Open some apps and see what happens.

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

## Operating System

The Operating System(OS) is software used to manage the computer.  The OS have the following functions.

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.
Security
Manages accessing authorization of data and hardware.
User Interface
A computer is operated by GUI and CUI.

Operating systems of the following are broadly used.

PC
Windows, MacOS, Linux(Ubuntu, etc)
Smart Phone
iOS, Android (Linux is used for kernel)
Server
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 when neccessary.

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,、but let’s review.

• 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. Make `ex10-5.txt` inside the directory “fundamentals of information technology” we made (or any other directory you like), and write something.
2. Confirm the absolute path of `ex10-5.txt` via editor.
• With mi, it is displayed on top(/`automount...)`
• 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.  Even if the file has the same name, as long as it exists in a different directory it’s a different file.
• Alias adds a different name for the same file.  Even if the file name is different, it is still the same file.

There are cases when other users read and write the file, so there is the need to set accessing authorization to each file or directory.

(PPT版ダウンロード)

Normally, users work with their own directory and set the accessing authorization so that other users can’t overwrite any files.  However, if the settings are changed, a file can be accessed by anyone.  Let’s use the shared region and practice.

Exercise 10-6（☆☆☆☆）
1. Make `ex10-6.txt` write something, 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.  Let’s try doing this with a computer.

Exercise 10-7（☆☆☆）
1. Edit Exercise 09-6 and display the numbers from 1 to 30.
2. How should we draw the flowchart(the diagram below) of the program? What goes into condition and process part?
3. First, display Fizz when the number is divisible by 3, and display numbers when not.  Where should we place the conditional branch(in the flowchart)?
4. Make a 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 three is 0”.  The operant of a remainder is “%”.  When we want to find out the remainder of count, 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（☆☆☆☆☆）

Let’s make another game. Display numbers from 1 to 99, and add “Ooops!” after numbers in case:

• the number is divisable by 3, or.
• the number contains digit 3 (either the digit of 10’s place or 1’s place is 3).

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

Reference

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

## The Change of Values in a Variable

### Calculation using the Current Value

Data can be stored into variables by assignment.

When a result of some formula is stored into a varible, the “current value” of the variable can be used in the formula. For example, the following is an assignment statement for a variable `x`.

• `x = x + 1;`

If the original value of x is 2, first calculate `x + 1` which results 3, and then 3 is assigned to `x`. So after the statement is executed, the value of `x` will change to 3.

Exercise 09-1（☆）
1. Execute the following with console.
• `var x = 3;`
• `x = x + 1;`
• `x = x + 1;`
• `x = x + 1;`
2. Execute the following with console.
• `var x = 1;`
• `x = x * 2;`
• `x = x * 2;`
• `x = x * 2;`
• `x = x * 2;`

When writing statements like the example above, it is a waste of time to write the same variable twice.  Instead, the operator `+=, -=, *=, /=` … can be used.  For instance, x = x + 1 can be written as x +=1, or x = x – 1 can be written as x -=1.  There is a special operator for “adding 1″(`++x`) and “subtracting 1″(`--x`).  All of `x = x + 1, x += 1, ++x` have the same meaning. `x++` is also an operator for “adding 1”, but has a slightly different meaning (see the reference below).

### How to use the Debugger

A debugger can be used when we want to know which part of the program is running, or what value is inside a variable.

The following can be done with a debugger.

Pausing a Program, Step-by-step Execution, Resume
The program can be stopped by setting a breakpoint.  You can 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. Make `ex09-2.html` and fill in the following.
2. Make `ex09-2.js` and fill in the following.
3. Click the button several times.  What happened to the number?
4. Watch the video below while doing the following steps.
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 debugger), and call out `addCount(). `What change on the debugger screen?
9. The value of variables are displayed on the right section of the debugger.  “Scope” is a little difficult and won’t be explained in this class, but when a variable is declared inside a funtion, it is a funtion scope, and when a variale is declared outside any funtion, 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 that the value of `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, so check the value of  `count`.
14. Resume the program and check what number is displayed in the dialog.
15. You can turn off the break point by clicking.  Turn off the break point on the 4th and 5th line.

Reference

### Changing the Elements of 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. Make `ex09-3.html` and fill in the following.
2. Make `ex09-3.js` and fill in the following.
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 to 100.
5. In `setAttribute`, change the width size from the number `'800'` to the variable `w`.
6. In function `change`, write a statement “add 10 to the variable `w`” and change the function so that the image gets larger each time the button is clicked.
Exercise 09-4（☆☆☆☆）

Make a textbox, and add a function so that when a number is entered, the image gets larger by the value of the number.

### Adding Content to a Page

In Exercise06-8, we learned that the content of the webpage can be changed by using `innerHTML`. By assigning different values to `innerHTML` again and again, we can gradually change the content of a webpage.

Exercise 09-5（☆☆☆）
1. Make `ex09-5.html` and fill in the following.

2. Make `ex09-5.js `and fill in the following.
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. Make 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.

## Automatic Loops

In the exercise above, we must click the button multiple times to repeat the process.  Let’s try repeating the process several times with one click.

### “for” Loops

To repeat processes. we use the “for” loop.  A for loop is written as the following.

• `for ( initialization; conditoin; afterthought ) { process }`

This statement will be executed in the following way.

1. The “initialization” part is executed.
2. The “conditon” part is calculated.
3. If the condition is true, the “process” part is executed.
4. The “afterthought” part is executed.
5. The “conditon” part is calculated again. If it is true, the “process” and “afterthought” parts are executed again.
6. The step above is repeated while the condition is true. When the condition is false, we go to the next statement.

Exercise 09-6（☆☆☆）
1. Make `ex09-6.html` and fill in the following.
2. Make `ex09-6.js` and fill in the following.
3. Open the file and click the button.
4. Draw the following diagram on your notebook. Fill its blank boxes with sentences in `ex09-6.js`.
5. Replace `count <= 5` in the second line with `count >= 5`, reload, and click the button. Why the behavior changes like this?
6. Replace it with `count >= 0`, reload, and click the button. Why the behavior changes like this?
Exercise 09-7（☆☆☆☆）

Edit Exercise09-5 so that 100 lines are added at once when the button is clicked.

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 the image file in Exercise 09-3 would get larger and larger if using a for loop, but it won't work.  The repetition of the for loop is done in an instant, so to the naked eye it would seem as if only the last photo is displayed.  The proper way to do this will be explained in Appendix: Various Features - Iteration by Timer Events.

### "while" Loops and "do-while" Loops

"while" loops and "do-while" loops can be used for loops as well.  We can do the same thing with any of them, so use the loop you are most comfortable with.

"while" loops are written as the following.

• `while ( condition ) { process }`

"do-while" loops are written as the following.

• `do { process } while ( condition )`

The process is executed repeatedly while the condition is true.  With a "while" loop, if the condition is false in the first place, the process isn't executed at all.  With a "do-while" loop, the process will be executed at least once.

The "for" loop has the same meaning with the following "while" loop.

1. `initialization; while ( condition ) { process; afterthought; }`
Exercise 09-9（☆☆☆☆）

Rewrite the program with while loops, for Exercise 09-6 and Exercise 09-7.

Points to check
• What does `x = x * 2 `mean?
• How is a for loop written?
• What happens when the condition is false after initialization of a for loop?

# No.8 Quantity of Information

## The Quantity of Information

You may use the phrase “the file size is big”, or “the webpage is slow”, but the size of information can be measured in actual values.

Exercise 08-1（☆☆☆）
1. How many bits would be needed to distinguish blood types?
2. How many numbers of trials would be needed to find the blood type of a person with yes/no questions?  Draw a diagram of if statements and combine it so you can find out the blood type of a person.
3. Make `ex08-1.js`, and add function that when the button is clicked, the message “Your blood-type is ～” shows up.
4. Add a function that show the message “Enter yes or no”, when a word besides yes or no is entered.

### The Information Quantity in an Image

Let’s think about the information quantity in a bitmap image.

• A bitmap image is made up of pixels.
• In a black and white photo, every pixel is either black or white, so you can say it has the information of one bit.  In a colored photo, the information for color is needed for each pixel.
• The information quantity of the entire photo is the number of bits for each pixel multiplied by the number of pixels.
Exercise 08-2（☆☆）
1. How many kilo-bytes is a black and white photo with the size of 640×480?
2. How many kilo-bytes is a 16-colored photo with the size of 640×480?

## Text Encoding (Character code)

Converting letters that humans can read to data that can be processed by computers is called text encoding.  The  `<meta charset="utf-8"> `part of HTML we have been working with is a command specifying the text encoding.

Exercise 08-3（☆）

This exercise is meaningful only if you use Japanese (or other non-English) text.

1. Open a webpage with Firefox and change the text encoding from View→Character Encoding
2. Edit `introduction.html` with mi and try the following
1. Change the character encoding to EUC-JP on the toolbar, save the file and view the file with Firefox.
2. Change `charset="utf-8"` to `charset="euc-jp",` save the file and reload the page.
3. Return the character code with mi to UTF-8, save the file and reload the page.
4. Return `charset="euc-jp"` to `charset="utf-8",` save the file and reload the browser.

Emacs chooses a character encoding automatically when specified in c`harset, `so the Exercise above will always show the proper content.

## Compressing Data

Raw data may have statistical redundancy that can be reduced.  In such a case, the data can be compressed by saving the data in a different shape, to save space.

Exercise 08-4（☆☆）
1. Decode the following bit stream that has been compressed by Run-length encoding.
• The length of each run (successive 0’s or 1’s) is 3 bits.
• 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.

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

Photographs have different colors for every pixel, and is difficult to compress it to a small size when using a lossless compression, so JPEG is usually used.  In contrast, lossless compression is used for images such as illustration and logos, because the same color is used for a certain area and the outline is clear.

Exercise 08-6（☆）
1. Open the preview of your photo from your self introduction page.
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 the high and low quality files. Can you see the difference?
5. Compare the difference of file size with 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.
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 and display the thumbnail and original photo.

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 size of the Image

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

• The unit is pixels.
• If only one of the `width` or `height` attributes is specified, the other will be adjusted to match the other.

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

• Select the attribute with`document.getElementById()`
• Add `.setAttribute()`
• The arguements 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. Make `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. Make a button and call out `change()` when the button is clicked.(Remember to add the script element to read the JavaScript file)
Exercise 08-9（☆☆☆☆）

Make a textbox, and add a function which changes the width of the image 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.

Reference

Points to Check
• But is a bit?
• How do we calculate the file size of a bitmap image.
• What is character encoding?
• What is the difference of lossless and lossly compressions?
• What kind of image file is PNG and JPEG suited to compress?

# No.7 Conditional Statements

## Inputting Data

Humans operate a computer by using a mouse or keyboard.  This is called Input.  In contrast, a computer communicates with humans by displaying texts or images, and makes 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’ve 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. Make `ex07-1.html` and fill in the following.
2. Edit `ex07-1.js `and fill in the following.
3. Type in your name in the textbox and press the button.

To read values input by the user, we use `document.getElementById().value`.  This is different from `document.getElementById().innerHTML` , which we learned in the last lesson, as follows:

innerHTML
The content of the HTML element (tags excluded).
value
In case of `textbox`, the data input by the user. In case of other input elements such as buttons and checkboxes, it has different meaning.
Exercise 07-2（☆☆☆）

Make a new textbox for entering a word replacing “Hello”.  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!”.

### Entering Numeric Values

Numbers entered in a textbox is handled as a string literal.  When we want to calculate these numbers, we must use `Number()` (which we learned in the 5th lesson) and convert them into numeric values.

Exercise 07-3（☆☆）
1. Make `ex07-3.html `and fill in the following.
2. Make `ex07-3.js `and fill in the following.
3. Fill in a random number in the text box and click the calculate button.
4. Fix the program.
Exercise 07-4（☆☆☆☆）

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

Reference

## if Statements and Conditional Expressions

### How to write an if Statement

Programs are executed from up to down, but there is a method to write multiple commands and execute ones only matching the situation.  This is called a conditional expression, and in JavaScript the if statement is used.

Exercise 07-5（☆）
1. Make `ex07-5.html` and fill in the following.
2. Make `ex07-5.js` and fill in the following(note that there are two equal marks next to each other)
3. Type in the correct answer and click the button.  Try entering a wrong answer as well.

There are two ways in writing a if statement.

• Execute the command when the condition is true, and do nothing when false.
• Execute a command when the condition is true, and execute another when false.

The two ways are written as the following, respectively.

• `if ( condition ) { process }`
• `if ( condition ) { process1 } else { process2 }`
Exercise 07-6（☆☆）

Edit the previous file so the message “Wrong!” appears when the answer is incorrect.

### Relational Operators

In a program, numerical equality and inequalities are handled as operators as well as `+ - * /`.  To operate a  numerical equality and inequality, we use operators such as < > ==

These operators return booleans(true and false) as a result.

Example 07-7（☆☆）
1. Execute the following with console.
• `2==2`
• `2==3`
• `2!=2`
• `2!=3`
• `2<2`
• `2<=2`
• `2<=3`
• `'2'==2`
• `'2'===2`
2. Edit Exercise07-6 and change the conditional statement from true to false, and replace “Correct” and “Wrong ” with each other.

The reason why we use two equal marks is because one equal mark is the command that assigns a value to the variable.

Usually booleans are specified for the condition of an if statement, but it is not an error to write values of other types.  In that case, the value is converted into a boolean.  An assignment of a variable can be written for the condition as well, and the assigned value will be converted to a boolean.  So, if you make the mistake of entering only one equal mark inside the condition, no errors will occur but the program will most likely go out of whack.

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.

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.

Exercise 07-9（☆☆☆）
1. Draw the following image on paper.  Write “If the input equals ‘newspaper’ ” instead of “Condition”, and write “display ‘correct’ ” instead of “Process 1”.
2. Erase “Process 2” and draw the same diagram above in that place.  What should we write inside Condition, Process 1, and Process 2?
3. Edit the riddle program to match the diagram.
• It is annoying to write `document.getElementById('answer').value `each time, so you should assign a value to a variable first, and use the variable later.
• 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 part or the false part of an `if` statement, the {    } can be taken off. So, when another single `if` statemnet comes after `else`, we usually write `else if` as the following.

```    if (condition1) {
process1
} else if (condition2) {
process2
} else if (condition3) {
process3
} .....
.....
} else {
process_n
}
```
Exercise 07-10（☆☆☆☆）

Edit the program from Exercise  07-4 so that the following messages show up.

1. When the BMI is under 18.5, “underweight”
2. When the BMI is over 25, “Obese”
3. When the BMI is in between, “Normal”
• The first if statement should judge whether the BMI is under 18.5.
• If the BMI is over 18.5, the second should judge whether its under 25.

### Logical Operators

Another method when comparing three values is using logical operators.

This method is based on logic. Logic is the base of many subjects.

The following logical operators are used in JavaScript: &&(AND), ||(OR), !(NOT)

Exercise 07-11（☆☆）
1. Write a conditional expression of the following.
• `x `is larger than 1 and smaller than 10
• `x `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 an year is a leap year or normal year.

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

## Funtions

JavaScript is written in the event handler on a HTML file.  With Exercise 05-10, a program (`alert("Hello, world!");)` was written inside the HTML file, so we didn’t make a JavaScript file.

However, as the program gets longer and longer it will be difficult to do so.   Therefore, the program itself is gererally written in a JavaScript file and is called out by the event hanler.

There are cases when one webpage uses multiple programs, so there is a need to name each program.  A function is a bundle of statements that can be called out when needed.

Exercise 06-1（☆）
1. Make `ex06-1.js` and fill in the following.
2. Make `ex06-1.html` in the same directory, fill in the following and open the file via browser.

“Hello, world!” did not come up from the webpage.  When a `funtion { ... }` is defined, the  `{ ... }` part is not executed, but is registered as a function so it can be called out.  In this Exercise, `sayhello` is the name of the funtion.  We will learn why there are parenthesis written after the function name.

Registering a funtion like the exercise is called defining a funtion.

### Calling out Functions

Once a function is defined, the program can be executed when we want.

Exercise 06-2（☆）
1. Open the HTML file from the exercise, display the console and run the following command.
2. `Edit ex06-1.html` and add the following inside the body element and reload the page.
3. What happens when the line is changed to the following?

When we call out the funtion name+() , the funtion defined with that name will be executed.

During the last lesson, we learned that we call out the funtion `Math.sqrt` when calculating the square root of a number.  `Math.sqrt` and `sayhello` are both functions, but `Math.sqrt` is a funtion defined by the system, and `sayhello` is a funtion you defined by yourself.

Exercise 06-3（☆☆☆）

Make a funtion saygoodbye,  and set a button which when clicked calls out this funtion and shows the message “Goodbye.”.

Reference

## Variables

### Variable Declaration

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

We can make variables of our own.  To do so, 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 defined as a variable or funtion is called out, the Reference Error is returned.
• When a variable that has no value is called out, undefined is returned.(undefined is not an error)

### Assigning the Value of a Variable

Saving data inside a variable is called assigning a value.  We write `variable = value;` when assigning a value, and `var variable = value; `to  define a variable and its value at once.

Exercise 06-5（☆☆）
1. `Make ex06-5.js and fill in the following.`
2. `Make ex06-5.html` and fill in the following.
3. First click on Greetings.  Then click on Taro→Greetings→Hanako→Greetings.  What value is inside who and why?
4. `Edit ex06-5.js` as the following and click on Taro→Greetings→Hanako→Greetings.  Is there any difference?

The following rules exist on where to define the variable.

• A variable used with more than one funtion needs to be defined outside the funtions.(Generally written on the top of the JavaScript file)
• A variable used with only one function should be defined inside the function.
Exercise 06-6（☆☆☆☆）

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

Reference

## Argument of a function

On the Exercise, we made two different funtions for taro and hanako.  This wasn’t so difficult because there were only two people, bu what if there were tens or hundreds?

An arugument is used to process multiple data with one function.

• When calling out a function, the data or variable that we want to pass on is written inside the parentheses.
• When defining a function, we write a variable inside the parentheses.  The value of the data input on the call out of a funtion, is automatically inserted to this variable.
Example 06-7（☆☆）
1. `Make ex06-7.js` and fill in the following.
2. `Make ex06-7.html` and fill in the following.
1. What happens to variables x and who when Taro is clicked?
2. Use function `someone` and make a button that greets “Rei”, “Shinji”, and “Asuka”.

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

## Editing the Page with JavaScript

JavaScript can read and change what is displayed on the webpage.  To do so, we need to use the following two methods.

• In the HTML file, we mark the place where we want to edit.  There are a few methods to do so, but in this class we will be using the id attribute.
• In the JavaScript program, we use the value `document.getElementById().innerHTML.`

For now, let’s look at the example.

Exercise 06-8（☆）
1. `Make ex06-8.js` and fill in the following.
2. `Make ex06-8.html` and fill in the following.
• The id attribute and class attribute are alike, 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 edited with JavaScript by using `document.getElemetById().innerHTML.`  This can be used like variable, and when a new value is assigned, the display on the browser will change as well.

`document,` `getElementById(),` `innerHTML` have the following meaning.

• `document` : The source of the page displayed
• `getElementById()` : A function which finds the specified ID
• `innerHTML` : The content with tags excluded.

By connecting these with a period, the browser will “fetch the content of the specified ID from the source of the current page, and exclude tags”.  To understand the meaning of the period we must study “Objects”, but will not go so far in this class.

Exercise 06-9（☆☆☆）
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 no your self introduction page as the following: `<div id="..."><img ...></div>`
• A div element doesn’t have any functions by itself, but is used to add id and class attributes.
3. Make a new JavaScript file, and make a funtion that edits the content of the div element, to change the img element from the first photo to the second photo.
4. Make a script element inside the head element, to read the JavaScript file we just made.
5. Make a button(above or below the photo) that corresponds with the funtion you made.
6. Open the file via browser and confirm that the photo changes when you click the button.
7. Make a button that returns the photo back to the original.

## Executing a Function with a Timer Event

By using the Timer event, we can execute functions by time.

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 milliseceonds you want to wait.

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

Exercise 06-11（☆☆☆☆☆）

Edit Exercise 06-9 to automatically switch back the photo after you click the button.

Points to check
• What is a function?
• How do you define a function?
• What is a variable?
• How do you declare variables?
• 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

## JavaScript

In a web page, we learned that HTML is used to define the structure, and CSS is used to define the design.

However, with only HTML and CSS, you can’t add movement to the page.

To create an interactive webpage, we must write a program.  One programming language used on web is JavaScript.

JavaScript and Java is a different language.  Be careful when buying a book of reference.

”Program” and “Script” is basically the same thing.  Short programs are usually refered to as scripts.

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

Exercise 05-1（☆）
1. Make “`ex05-1.js"` and write the following.
2. Make “`ex05-1.html"` in the same directory and write the following.
3. `Open ex05-1.html` via browser.
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 begginners make.

## Executing a Program

### Procedures

JavaScript is a language that instructs browsers to execute commands. For instance, “alert” is a command that displays a text inside a dialog box.

Browsers execute programs when a script element exists.  when there are multiple commands, they will be executed in order(up to down).

Exercise 05-2（☆☆）
• `Edit ex05-1.html` and write the following.  What changed?

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

Exercise 05-3（☆）
2. Type in  `alert('Hello, world!');`
3. Execute the program and see what happens.

Reference

### How to use Console

When there are errors in a program, the program would (obviously) not move.  If there are no clues when searching for the error, it would take a tremendous amount of time and effort, so browsers have the function to give us error messages.

Exercise 05-4（☆）
1. Select Tool→Web Developer→Web Console
2. `Edit ex05-1.js` and change alert to “alart”
3. Reload the browser and confirm the console.
4. `Fix ex05-1.js`, reload the page and confirm the console.

Reference

## Basic Syntax

We will study JavaScript from now, and here are some basics 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 commnets, and other parts of the code must be written with ASCII characters.
• 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, but you should to prevent any trouble.
Exercise 05-5（☆☆☆）
1. Open the following JavaScript files via browser and save the file(File→Save as…)
2. Make a HTML file that reads these JavaScript files.
3. Open the HTML file and check the errors on the console.
4. Fix the errors.

We went through the trouble 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 scrathpad.

## Calculating a Formula

### Easy Formulas

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

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

Exercise 05-6（☆）
• Edit ex05-1.js and write the following. Open 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.

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 comes back 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.

### Calcuting via Console

It is annoying to edit the Javascript file each time we want to evaluate an equasion.  Instead, we can click on the bottom line of the console, type in the function, and 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 a alert box.  This function returns a special value undefined.

Exercise 05-9（☆☆）
1. Calcutate the 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 tje result cannot be displayed as a numeral.

### Data Type

There are various types of data that can be used with JavaScript, and we call this data type.  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 ’12’ is a string literal made of the letter ‘1’ and ‘2’.
• `+` is the simbol 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（☆）

Execute the following functions via console.

• `2+3`
• `'2'+'3'`
• `Number('2')+Number('3')`
• `'2'+3`
• `Number('2')+3`

## 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 you want to execute on the cue of an event, you must define the event handler that corresponds with HTML elements.

Exercise 05-11（☆☆）
1. Make the file` ex05-11.html` and fill in the following.
2. Open the file via browser and click on the button.

3. Make a copy of the input element and edit onclick to ondblclick. and 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.

`onclick` is generally used for events concerning buttons, and other elements will work too as long as the event handler is correct.

Exercise 05-12（☆☆☆）

Edit the header “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.

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…

Points to Check
• What is a program used for?
• In what order are the statements inside a program executed?
• What does “calling out a funtion” 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.  But there is a limit to what you can do with HTML, and is general to combinate HTML with other sorts of files.

The folllowing files are commonly used.

Style Sheet(CSS)
Used to define the visual layout of a webpage.
Script(JavaScript)
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.

## Images

### Analog and Digital

Computers used nowadays mainly process digital data.

Exercise 04-1（☆☆）

Reference

### 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 to a file.
• Using whitespaces or symbols in a file name will complicate things, so make sure to use only alphanumeric letters.
4. Open the file by double-clicking.  “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 the 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 specifying 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 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 a image file from the web, we must follow the rules of citation or obtain 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 may be functions that won’t work.  When writing a css file, remember to check whether each funtion will work 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.

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

### Syntax of CSS

In a CSS file, we define “where” and “which” style we want to use.

“where”
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.
“what”
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.  Comments can be written by enclosing a text with /*                  */.

Excercise 04-4（☆）
1. Make the file “mystyle.css”(vai 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 changed.  If nothing changes, 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.

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

1. Disassemble the primary colors of light into red(R), green(G), blue(B).
2. Set the brighness of each color in the values between 0-255.
3. Convert each of these values into hexadecimal numbers(00-FF).
4. Write the 3 hexadecimal numbers in the order of RGB, and make a hexadecimal number with six digits(000000-FFFFFF).

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

Excercise 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 are dispayed.

Reference

### Defining Borders

The class schedule looks funny without borders, so let’s add some.

Exercise 04-6（☆）
2. Check out the Reference(border property) and set a border of your choice.

### “class” Attribute and Selectors

The 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 the “td element” to important.
3. Choose classes that aren’t that important 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 and make the class important.  What color is displayed?
2. Edit mystyle.css to display 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 Inspector for CSS

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.

Rules
Lists all the rules that apply to the selected element.
Computed
Lists all CSS properties and their calculated 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.

[quicktime]http://ipl.sfc.keio.ac.jp/text/info1/resources/02.mov[/quicktime]

Exercise 04-10（☆☆）
1. Open your self introduction page and display the information of the header(h1) using inspector.
2. Click on the color property and swich 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.

Reference

## Web Accessability

HTML describes the structure of the webpage semantically, and a style sheet is used to apply 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 infomation to millions of people, and to do so the method of displaying the information should be able to vary depending on the recipient.

Web accessibility refers to the practice of removing obstacles for people with disabilities, from accessing the web.

Excercise 04-11（☆☆☆☆☆）

Try using the web accessability checker below.

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

# No.3 How the Web Works

### HyperText

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

Exercise 03-1（☆☆☆）
1. See how to write links from the Reference.
2. Search and link the homepage of your elementry, junior high, and highschool 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 authorization?  According to the Copyright Law, it is interpreted that there are no problems, but if there are any specifications you should respect them.

### Specifying an URL

An URL is like an address of a webpage.  For example, the URL of SFC’s homepage is `http://www.sfc.keio.ac.jp/`

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 a encrypted page(like netbanking) we use “https:”.  When opening a file we use “file:”, and the browser will fetch the file without connecting to the internet.
• The host is the name of each computer, and specifies which computer to 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 the details of 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 an house in the neighborhood, we can say, “two houses next door from here”, 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-2（☆☆）
1. Access `http://itclass.sfc.keio.ac.jp/guide/index.html.en`
2. Display the source of the page by using inspector, and see how “Students who entered 2014 or after” is linked.
3. Click on “Students who entered 2014 or after” and examine the URL.

`http://itclass.sfc.keio.ac.jp/guide/index.html` 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 `http://itclass.sfc.keio.ac.jp/guide/index.html`

Good Poins of an Absolute URL
Can specify any webpage in the world.
The same URL can be used to be linked from any other page.
Good Points of a Reletive URL
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.

You will understand the rules of URL better after you study the next “File System” part.

You can access `http://itclass.sfc.keio.ac.jp/guide/index.html` from `http://itclass.sfc.keio.ac.jp/` or `http://itclass.sfc.keio.ac.jp/guide/` too, but this happens because you are relocated from a different page, and the actuall URL is  `http://itclass.sfc.keio.ac.jp/guide/index.html`

## File System

To learn how to write the “path” of a URL, we must learn how a computer manages files.  A file system on a computer controls how to store and retreive data from inside a disk.

The relationship between an URL and a file system is explained below.

• 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 abosolute 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.
• 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-3（☆☆☆）
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.
4. Make a new directory “dirA” under the directory we have been working with.
6. Edit link.html to correctly jump.
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 to correctly jump.
Exercise 03-4（☆☆☆☆）
1. Let’s make a web version of the “treasure hunting game” introduced on the slides.  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 `~/Desktop/info1` is the directory we made with the exercise on the slides.  The “~” represents your home directory.
• `cp` is a commpand 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” inside “islands”, and fill in the following.
5. Make another “map.html” file inside “island-a” (which is inside “islands”) , and fill in the following.
• A header “Map of Avalon”.
• Links to three harbors, “port-a”, “port-b” and “port-c”.
• A link that jumps back to starting point(“map.html” inside the directory “islands”).
6. Make yet another file “map.html” inside islands→island-a→port-a, and fill in the following
• A link to file “empty”, which shows the text “Treasure Box”.
• A link returning to “Map of Avalon”.
7. Make pages for ohter islands and ports in the same way explained above.
8. Try to make a shortcut from one port to another port in another island.

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

## 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 may be able to access 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 CNS, we can make a file accessible by placing a file 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 `http://web.sfc.keio.ac.jp/~(login ID)/(filename)`

Excercise 03-5（☆☆）
1. Make “`ex03-5.html"` and fill in the following.
2. Change “foo bar” to a word of your choice.
3. Move this file under “public_html”.
4. Access `http://web.sfc.keio.ac.jp/~(login ID)/ex03-5.html` with a browser.

The access authorization 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 transfered or compressed, the access authorization may be set so that only you can access it.  We will learn about the details of access authorization 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” under hobby, the URL you should access is `http://web.sfc.keio.ac.jp/~(login ID)/hobby/music.html`

Exercise 03-6（☆☆）
1. Make a directory “info1” under “public_html”.
2. Place “ex03-5.html” inside “info1”.
3. Did the URL of “ex03-5.html” change?  Try accessing the file with a browser.  Try accessing your neighbor’s as well.

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

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

Exercise 03-7（☆）

We are sorry that this exercise is only available in Japanese.

If you uderstand Japanese, “情報倫理デジタルビデオ小品集３” can be played on the iMac(Desktop→`Share_zmac``index.html). ` Watch the following parts and summarize 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.)

Excersise 03-8（☆☆）

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

Points to Check
• What is the difference between a HyperText and a normal text?
• What is the difference between a 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 exposed to the internet?
• What kind of rules are there to the Copyright Law?
• Are there any exceptions in the Copyright Law?

# No.2 HTML

## HTML

### Source of the Page

In the last lesson, we learned that looking at a word processor file through Terminal and Word was different.  The same goes for web pages.

Exercise 02-1（☆）
1. View a web page from Firefox, right click and select “view page source”
2. Do you see the relationship between the source and the actual page?

The file that is actually saved in the computer as a webpage is the source.  The webpages you usally see are pages that have been analyzed and converted by the browser, so it is readable for humans.

A file that is waiting to be processed (not only HTML files) is called the source file.

In the case of webpages, the source is written in a language called HyperText Markup Language(HTML).  Let’s try making a simple webpage.

Exercise 02-2（☆）
1. Start-up the text editor, write the following, and save the file as ex02-2.html.
2. Open the file via browser.
• You can open the file by double clicking.
• If Safari starts up, make the default browser Firefox by clicking preferences, select the Advanced panel, click the General tab and then under the System Defaults section, click the “Check Now” button.
• If mi starts up, drag and drop the file icon on Firefox.  You can also right click the file, click on “open with”, and select Firefox.
• If no applications start-up, make sure the filename extension is “.html”.
3. The content of the file should come up, but all the letters are the same size and shape, and ins’t COOL.  Let’s try editing the file like the following.

4. Save the file, and reload the page.
5. Let’s make “foo bar” and “abcdefg” into a list. Edit the file like the following.

6. Save the file, and reload the page.
7. There are many rules and restrictions to HTML.  Almost any browser would display the page with no problems, but let’s write it correctly.
8. Edit the page to match the code above, save the file, and reload the page.

There are many differences between opening a file with a text editor and a browser.  Looking at a HTML file through a browser is like watching a stage from the auditorium, and the other way around for a text editor.  When looking at the auditorium from stage, you can see all of the gimmicks that make up the stage.

### Markup Language

HTML is a type of “Markup Language”.  A markup language is a language that annotates text so a computer can analyze it.  The difference from a word processor is, a markup language annotates text while writing the file, so the complete form is only viewable after the file is made up

• The <h1></h1> on the both sides of “test” isn’t displayed, but indicates that the text in between is a heading
• The browser analyzes this instruction, and displays “test” in large letters.

Reference

## Grammar of HTML

### Elements and Tags

The annotations of HTML represent the structure of the webpage.  Every sentence  that is devided by an annotation is called an “element”.  For example, a header or table is an element.

There are times when a element is included in another element.  For example, there is an item element (li) inside a list element (ol). The webpage itself is a html element, and every other elements are included inside the html element.

An element is partitionated by tags.  For example, <ol> and <li> are tags.  A keyword surrounded by “<>” is called a tag.

Every element has an opening tag and a closing tag. For example, a header element (h1) starts with a opening tag<h1>, and ends with a closing tag </h1>.  When writing a closing tag, a “/” is put before the element name.

Some elements don’t have closing tags.  For example, `<meta charset="utf-8">` is a meta element by itself.

An attribute can be written in an opening tag to provide additional informaion to elements.  Multiple attributes can be declared by seperating each attribute with a space.  In the case of `<meta charset="utf-8">`, “meta” is the element name, “charset” is an attribute,  and “utf-8” is the value of the attribute.  The available attributes depend on the element.

Exercise 02-3（☆☆）
• What kind of elements are there in the HTML file we made in Exercise02-2?  Divide each element into boxes.

To be percise, the `<!DOCTYPE html>` on the first line is a declaration, not an element.  This declaration shows that the file is following the grammers of HTML5.  A browser first reads the declaration and analyzes the file according to the grammers of the declaration.

Reference

Browsers don’t read line breaks, so if you want to start a new line, you must type in a paragraph tag <p> or line break tag <br>.

When creating a webpage, there are times when you’d want to write a comment that doesn’t show up on a browser.  In such a case, a comment tag “<!– –>” is used.  Text written between a comment tag doesn’t show up on browsers.

### Different Kinds of Elements

There are many types of HTML elements, and is almost impossible to remember all of them.  Instead, let’s learn how to search tags when you need them.

Exercise 02-4（☆☆☆）Search the following elements by using HTML Reference
1. Search the following elements by using HTML Reference
• paragraph
• unordered list
• ordered list
• table
2. Start-up the text editor, make a new file, and write the following.  We will use this file again, so let’s name it  `introduction.html`.
3. Tag “Introduce yourself in this space” with a comment tag, and make sure it ins’t displayed on the browser.
4. Write the following inside the body tag.
• Make a headline    Ex. “Keio Taro’s Self Introduction”
• Make a list of the elementry school, junior highschool, and highschool you graduated from
• Make a definition list of your favorite book or music.
• Make a table of your class schedule.
Exercise 02-5（☆☆☆☆）
• Read the reference and write an html file that is displayed like the following.

x2+y2=z2
This class is Fundamentals of Information Technology, and is boring very interesting.
.tfel ot thgir morf nettirw eb ot desu esenapaJ

The current version of HTML is 5.  You may find articles with old HTML elements, but these elements will be unusable in the future, so let’s use HTML5 elements if possible.

### input elements

The input tag specifies an input area where users can enter data.

Originally, the input element is a part of the form element, but it can be used independently.

Exercise 02-6（☆☆☆）
1. Webpages have many types of inputs, and most use input elements.  The type of input element can be specified by the “type” attribute.  Make a new file, name it ex02-6.html, and write the following.
2. The width of the textbox is specified by the “size” attribute.  Edit the file and adjust the textbox to 50 letters.
3. Search using HTML <input> type Attribute page of the reference,and create a password input box, number input box, checkbox, and a button.
• To display a text for the button, change the “value” attribute of the “input” element.

Buttons and textboxes from the exercise above don’t have any functions, so nothing happens even if you input data.  To add a function, we must use a different language called “JavaScript”.  On the second half of the semister, we will study “Javascript” and process some data.  In Fundamentals of Information Technology 2, we will study how to send and process data on a server.

### How to use Inspector

Firefox has a tool that displays the relationship of HTML and the actual screen.  Click on Tools→Web Developer→Inspector

•  By moving the cursor when the inspector is in use, you can see which part of the HTML  actually corresponds with the screen.
• There is a function that displays the overlap of elements in 3D.

Reference

Points to Check
• What is HTML used for?
• What is the difference between a word processor and a mark-up language?
• What is the relationship between elements and tags?
• How do you make an ordered list?
• How do you make a button?