IT581: Practicum in Web Development, Summer 2015 (Hybrid)

Introducing JavaScript

The three Layers of the Web


What is JavaScript?

Program source code written in JavaScript can be incorporated directly into an HTML document. It will automatically be executed by the browser when the page is loaded--if the browser is one with JavaScript support. Using JavaScript, you can make Web pages that interact with the user and vary their content.


What can you do with JavaScript


Incorporating JavaScript in HTML

There are several ways of incorporating JavaScript program code into Web pages.

  1. First, many HTML elements may have attributes that contain JavaScript instructions. Hyperlinks and buttons are most frequently used for this purpose.
  2. A second technique is to place the program code inside <script </script> tags, the same way we embed stylesheets in a document. Unlike stylesheets,scripts can be placed in the body as well as in the head.
  3. Third, the JavaScript can be stored in a separate file and a special command included in the document that tells the browser to get it.

We will begin with the second method. A script section in the HTML document is written as follows:

  <script >

    // JavaScript code goes here
    // These three lines are comments.  A JavaScript comment
    // begins with // and continues to the end of the line.

  </script>


Hiding JavaScript code

Some browsers do not recognize JavaScript. If they load a page that contains JavaScript, they will ignore the <script> and </script> tags and show everything in between as ordinary text content.

Similarly, the W3C validator may try to inspect the script text. It it contains text that looks like HTML tags, the validator will report errors.

Fortunately, there is a solution that will hide the script text. The solution lies in JavaScript comments. JavaScript comments normally begin with two slashes, as indicated above. However a line beginning with <!-- is also a comment if it immediately follows the <script> tag. So we will always begin an embedded script with a comment that begins with <!-- and end it with a JavaScript comment of the form //-->,

To a browser, the script is a single long HTML comment.


  <script >
  <!--

    // JavaScript code goes here
    // It is hidden from browsers that don't understand it
    // and from the W3C validator
    // because this inside looks like an HTML comment to them

  //-->
  </script>


JavaScript Statements

A JavaScript program is made up of statements, commands that specify some action and what to perform the action on. Each statement ends with a semicolon.

The document.write method

The first JavaScript command we'll use is called the document.write method (or simply write statement for short). A write statement has the form:

     document.write("message to be displayed");

The quoted text contained within a write statement becomes part of the page when that statement is executed. For example, the above write statement would cause the message "message to be displayed" to appear in the page. Text within a write statement can contain HTML tags, with the resulting text being rendered as if it were entered directly into the page. For example, placing the following JavaScript code in the BODY of a Web page


  <script>
  <!--
    document.write( "Hello, and welcome to my <em>Web Site</em>.<br>" );
    document.write( "I hope you like it!" );
  //-->
  </script>

has the same effect as placing the following directly into the page.

    Hello, and welcome to my <em>Web Site</em>.<br>
    I hope you like it!

Here is a complete web page with the above script code. Be sure to compare the displayed page with the source code.



The prompt method

document.write by itself doesn't let you do anything that you couldn't do with HTML alone. But JavaScript also has other instructions that cannot be accomplished with just HTML.

The JavaScript prompt method opens a dialog box on the screen in which the user can type some text. The method is called prompt because it displays a message in the pop-up box that tells the user what to enter. In computer programming, such a message is called a prompt. In the following example, the user is prompted for their name, and then a message incorporating that name is displayed in the page.

<script>
  <!--
    document.write( "Hello again " );
    document.write( prompt("Please enter your name", "first name") );
    document.write( ", welcome to my Web page." );
  //-->
</script>

The prompt method has two inputs. The first is a message that will appear in the dialog box, explaining what value the user is supposed to type in. The second input initially appears in the input area. If the user clicks the OK button without entering a value, this original value will be returned. Otherwise, whatever value they enter into the input area will be returned when they click the OK button.

The result of the prompt function is a string, a group of characters, such as "I hope you like it!" is used in a document.write the same way a quoted message is.

Notice how the first line is displayed and then there is a pause in the display until after you finish typing the name and click OK.

Example

Here is our example document with this script added. (Be sure to look at the source code.)



Variables and assignments

Variables in JavaScript are created, or declared, by using the word var followed by the name of the variable. For example, the following fragment of JavaScript tells the interpreter to create two variables, first_name and age.

      var first_name;
      var age;

Varaibles can hold different types of data, such as strings or numbers. You don't have to specify the data type when you declare a JavaScript varialbe.

      first_name = "Sam";
      age = 23;

Here an example greetings program revised to use some variables.

<script >
  <!--
    var visitor;
    visitor =  prompt("Please enter your name:", "Your name here");

    document.write(  "Hi "  );
    document.write(  visitor  );
    document.write(  ", how do you like my Web page?<br>"  );
    document.write(  "Thanks for visiting.  Come back again to see if anything is new.<br>  Goodby for now " );
    document.write(  visitor  );
  //-->
</script>

The first line creates the variable visitor. The variable name, visitor, is not in quotes. This is how the JavaScript interpreter knows it is a variable and not to be taken literally.

In the second line, whatever the user types in response to the prompt statement will be stored in the variable (memory box) named visitor. Then when visitor is used in the fourth and seventh lines, the stored text is written.

Example

Here is a complete document with the above program added.



Variable names

Variable names in JavaScript--and in all programming languages--cannot be just any combination of characters. They must meet certain requirements. In JavaScript, variable names:

If you try to use an illegal variable name, it will usually cause an error. Unfortunately the console error message will not tell you specifically that it is an illegal variable (how can it know something was supposed to be a variable) but will report some problem (such as "missing semicolon") on or around that place in the script.



Declaring variables

So far we've used separate statements such as

   var my_word;
    my_word = "Hello";

to declare variables and assign values to them. It is also possible to combine the steps into one statement, as in:

    var my_word = "Hello";

Each variable should only be declared once, the first time it is used.



Writing multiple items with one document.write

It's tedious to type several document.write statements to write a sentence into a document. Fortunately there are ways to speed this up. One way is to give document.write a list of several inputs, separated by commas. For example,

    document.write( "The value is: " );
    document.write( my_word );
    document.write( "." );

can be condensed to

    document.write( "The value is: " ,  my_word ,  "." );

Note: The extra spaces around the commas are just there to make it easier to read. They are not necessary.



Using JavaScript Comments

As your programs get longer, it is useful if you can annotate them with comments that help explain what is going on. In JavaScript, a comment is a line that begins with //. Anything from the // to the end of the line is not executed, but is there for you to see when you view the source code.

You can write a // comment on a line by itself, or at the end of a statement line, but it has to be the last thing on the line.

// make some variables
var a = "Hello ";
var b = "sailor.";

// use them
var c = a + b;   // concatenate their values
alert(c);        // Show the result


The alert method

Another way of displaying something is to use the JavaScript's alert method. Alert pops up a box with a message in it, called an alert box. The user must click OK for before the program will continue. The user cannot change or enter anything.

alertmay have only one input argument in the parentheses, the message to be displayed.

    alert("Something");

produces



Using an expression in alert

The alert method is not limited to displaying a single variable or string. It can be given an expression, as long as the result of that expression is a single string. The example could be rewritten as

        var part1 = "house";   //Create variables and assign values
        var part2 = "boat";     //Two steps combined into one

        alert(part1 + part2);   //computer contatenation before alerting

Example

Here's an example that uses all the JavaScript commands we've learned so far: variables, strings, prompt, alert, and document.write.

    var greeting;
    var whozit
    greeting = "Hiya ";
    whozit = prompt("Please enter your name", "In here!");
    alert (greeting + whozit);
    document.write("This page is customized for ", whozit, ".");

Here is example incorporated into a page.



Prompting for numbers.

When you use the prompt function to get a value from the user, the result is always a string, even if it is made up of digits.

  var length;
  var width
  length = prompt("Enter length of rectangle.", "");
  width = prompt("Enter width of rectangle.", "");

  //Multiply to calculate the area
  //JavaScript realizes it needs to use numbers with *.
  var area = length * width;
  document.write("The area is " ,  area ,  "<br>");

  //In this one, the variables are used with a +.  it is regarded
  //as string concatenation because they came from using prompt
  //and are originally strings, just as if they were quoted.
  var perimeter = length + length + width + width;
  document.write("The perimeter is " ,  perimeter ,  "<br>");

The parseFloat function

The solution is to use the parseFloat function. It tells JavaScript to turn its input into a number.

As long as the input to parseFloat begins with something that can be a number, it will return the longest number it can make. But if the input does not begin with something that can be a number, parseFloat stops and retuns the special value NaN (Not a Number). Compare the results of the following two JavaScript statements.

  alert(parseFloat("abc12"));
  alert(parseFloat("12abc"));

Example

  var length;
  var width
  length = prompt("Enter length of rectangle.", "");

  //Tell JavaScript to ensure the value is a number, not a string
  length = parseFloat(length);

  //You can also do it all in one statement
  width = parseFloat(prompt("Enter width of rectangle.", ""));

  //The rest is the same
  var area = length * width;
  document.write("The area is " ,  area ,  "<br>");

  var perimeter = length + length + width + width;
  document.write("The perimeter is " ,  perimeter ,  "<br>");

Here is example incorporated into a page.



JavaScript (built-in) Function: Math library

A function is a reusable code-block that carries out some specific task for you. Image: A function returns a single value

Like methods, functions must be provided with arguments - inputs to function - in the parentheses following the function name.

The result is usually a single value, called the return value, that is used in an expression the same way a numeric literal or variable would be used.

The Math library of functions

The Math library of mathematical functions provides the functions that you would find on a scientific calculator, including the square root function as well as logarithmic, exponential, and trigonometric functions. These functions all have names beginning with Math. This means that they are part of a JavaScript object named Math, but you can just think of it as part of their name.

Rounding to a whole number

The Math library includes a function named Math.round that will round numbers for us. It should be given one numeric argument, and it returns the input rounded to the nearest whole number. The input can be an expression. For example,

    Math.round( 3.14159265358 ) is 3
    Math.round( 8.707 ) is 9
    Math.round( 2.2 *3 ) is 7    

Rounding to a number of decimal places - the toFixed() method

Money is usually reported in dollars and cents, such as $75.45, not rounded to the nearest whole dollar.

The store will lose if a price of $75.45 is rounded $75 - and the customer will lose if $75.65 is rounded to $76.

In JavaScript 1.5, there is a method called toFixed that will format a number to a designated number of decimal places.

It will add zeros as necessary.

For example

    var amount = 1234.7654;
    alert(amount.toFixed(3)); //shows 1234.765
    alert(amount.toFixed(2)); //shows 1234.77 
    alert(amount.toFixed(7)); //shows 1234.7654000

Warning: The toFixed method is only available in JavaScript 1.5, not in earlier versions.

Hence it is only available in browser versions Netscape 6, IE 5.5, and newer versions or browsers.

If you are creating an application that needs to be be accessible to outdated browsers, you must use a different solution.


Quotation marks and strings

So far we have been using double quotation marks around strings. For example:

   var something;
   something ="A silly string";
   alert(something);
   document.write( "Using double quotes.");

JavaScript also allows you to use single quotation marks.

   var something
   something ='A sillier string';
   alert(something);
   document.write( 'Using single quotes.');

When to use single or double quotation marks:

In ordinary JavaScript programs between <script> and </script> tags, you can use double quotes. You can also use single quotes if you prefer.

However, a program can also be written as the value of an HTML attribute. In that case use single quotes because the entire program is between double quotes.

Warning: When you use single quotes, don't use an apostrophe in a string.


Events in HTML documents

When you click on an element of a web page, such as a button or link, or type text into a box, you are initiating an event - the occurence of an action on the document that can be detected and responded to.

What happens in response is called handling the event. The browser automatically handles some events - when you click on a hyperlink, it fetches and displays the linked page. Some style rules, such as specifying a color for a:hover, indirectly tell the browser how to handle an event - in this case moving the mouse pointer over the anchor.

Most elements on a web page can have events associated with them. The events most commonly used are clicking on the element, moving the mouse pointer over the element, and moving the mouse pointer away from the element.



Event handlers

You can define how a specific event is handled by using JavaScript. The JavaScript program that handles an event is called an event handler for the event. The JavaScript code is the same as what you have been using; you just need to know how to associate it with the event.

Event attributes

To tell the browser what JavaScript code to execute in response to an event, you make the code the value of a specific attribute that designates the event. These attributes always begin with the letters on. For the event of clicking, the attribute name is onclick. To handle the click event for a button, you would add the attribute as follows.

  onclick="//JavaScript code to be executed when the element is clicked."

Quotation marks in event handlers

As with any attribute, the value for the event handler must be enclosed in double quotes. This means that you cannot use double quotes in the JavaScript code. Fortunately JavaScript allows either single or double quotes around strings, so you can use single quotes inside event handlers.

Example

In this example, the strong element has an attribute to handle the onclick event. The attribute value is the JavaScript that will be executed when the text is clicked, in this case executing an alert function.

  <p>
   This is an event example.  
   If you <strong onclick=" alert('Hi'); ">CLICK HERE</strong>, 
   you will see a message.  (Note: The pointer doesn't change to a hand because the 
   text is not a link.)
  </p>

This is an event example. If you CLICK HERE you will see a message. (Note: The pointer doesn't change to a hand because the text is not a link.)

Example 1 in a complete page.

The event is handled by the JavaScript statement inside the double quotes in:

      <strong onclick=" alert('Hi'); ">

The string in the alert is enclosed in single quotes instead of double.

The double quotes are part of the HTML portion:

      <strong onclick="  ">

The JavaScript statement is inside the double quotes:

      alert('Hi');

Helpful hint

It is easy to make errors when typing an event handler, especially with all the consecutive punctuation symbols at the end. In the example, there are five, includng two different types of quotation marks:

       '); ">

To reduce errors



Changing style values

It is possible to change the values of style properties for parts of a document.

Overall, this a complex topic, involving the Document Object Model (DOM).

However if we limit ourselves to elements with an ID we can make some changes fairly easily. The first challenge is to know the names that can be used for the properties from within JavaScript.

JavaScript names for style properties

To get the name of a style property as used in JavaScript:

  1. take the original style rule from the CSS declaration
  2. capitalize the first letter following each hyphen
  3. then delete the hyphens

Here are a few examples:

CSSJavaScript
background-colorbackgroundColor
list-style-typelistStyleType
colorcolor
font-sizefontSize

Identifying an element in JavaScript: this

An event handler for an element can refer to the same element by using "this"

Specifying a style property

To specify a style property, use ".style.property_name".

For example, the background color of an element could be set to red using

    this.style.backgroundColor='red';

Example - Changing a style property

The button in this example changes its own background color and font-size when clicked.

   <p style = "backkground-color:blue" onclick="this.style.backgroundColor='red';  this.style.fontSize='large';" >
   Integer lorem nisl, tincidunt at, vulputate venenatis, auctor quis, elit. 
   </p>

 

Integer lorem nisl, tincidunt at, vulputate venenatis, auctor quis, elit.

The example as a complete separate page. Be sure to look at the source code.


Identifying an element in JavaScript:document.getElementById()

Any HTML element that has an ID can be accessed in a JavaScript program by using the document.getElementById() method. (Take careful note of the case.) Usually it wil be assigned to a variable.

For example, if an element such as a paragrpah has id="introduction", it might be assigned to a variable for use in a program as follows

  var intro_part = document.getElementById("introduction");

Example - Changing another element's style property

When the button is clicked, the onclick event handler changes the background color of the heading.

   <h2 id="test_spot">Color Test area</h2>

   <input type="button" 
             value="red" 
             onclick="var target = document.getElementById('test_spot');
                      target.style.backgroundColor='red';" />

Color Test area

Complete example page. Be sure to look at the source code.


Guidelines

Comments to: dong@hood.edu
Last Modified: 22 July 2015. 16:34