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?