Richland College Multimedia Learning Center

JavaScript, jQuery, and React
Home e-Handouts and Assignments Syllabus Resources Student Sites Other Classes RLC Multimedia
Updated 9/15/2020 at 11:50am

Variables, Functions, Objects, and Events


References


Introduction

JavaScript uses variables to store information in the computer's memory. A variable is a named storage area, which you can create in your JavaScript code. You often need to store some information in the computer's memory, in a variable, as you do things in the Web page.

Individual lines of code in JavaScript are called statements.

A grouping of statements into a named, logical unit of code is called a function.

JavaScript is object-oriented. An object is a single unit or component that contains functions and variables. The functions in an object are called methods, and the variables in an object are called properties.


Declaring and Using Variables

Now, let's talk specifically about variables. Variables:

Please note these points about variables and statements:


Statements, etc.

To review so far:

JavaScript uses variables to store information in the computer's memory.

Individual lines of code in JavaScript are called statements.

A grouping of statements into a logical unit of code is called a function.

You can create new text on a Web page with the write() method or the writeln() method of the document object.

To execute, or run, an object's method, you append the method name to the object name with a period, and include any information that is required to be sent to the method within the method name's parentheses. The information within the parentheses is called a set of arguments.

The write() and writeln() methods of the document object require that you put a text string in the parentheses as the argument. A text string is a sequence of characters enclosed with quotes. The text string that you provide as the argument is used by the write() or writeln() method to put new text into the Web page (document). For example, the code

  document.write("How are you today?");
instructs the browser's JavaScript scripting engine to put the text How are you today? into the Web page at the location where the code resides within the page's other (HTML and JavaScript) code.

You should note these points about text strings:


Defining and Calling Functions

A function is a (normally) named set of code that does something. In some other programming languages, a logical unit or grouping of statements is called a procedure. In JavaScript it is called a function.

Functions process information. All function names look like functionName( ). Note that there may or may not be something between the parentheses.

You can write you own functions. When you write your own function, you are defining it. When you use the function in your page, you are calling it.

Here are some things you need to know about writing your own functions:

Here is a sample of a function:

(Please note that the asterisk in the following code is the multiplication operator, and that the forward slash is the division operator.)

function convertToCentigrade (degFahren)
{
  var degCent;
  degCent = (5/9) * (degFahren - 32);
  
  return degCent;
}

And it is used in this page:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
	<title>Untitled</title>
  <script type="text/javascript">
    function convertToCentigrade (degFahren)
    {
      var degCent;
      degCent = (5/9) * (degFahren - 32);
      
      return degCent;
    }
    
    var FDegrees;
  </script>
</head>

<body>
  <script type="text/javascript">
    FDegrees = prompt("Type in a Fahrenheit degree to be converted to Centigrade", "");
  </script>
<h3>
  <script type="text/javascript">
    document.write(FDegrees);
  </script>
  degrees F is
  <script type="text/javascript">
    document.write(convertToCentigrade(FDegrees));
  </script>
  degrees C.
</h3>
</body>
</html>

You can see the above code in action here.

You should note these points about calling a function:


Built-In Functions

JavaScript provides many built-in functions. These functions are available for your use any time you need them.

One handy built-in function is alert( ). You saw alert( ) in the first section. The alert( ) function can be used for debugging your Javascript code, too.

Another handy function is prompt( ). The prompt( ) function asks the user for some information and then puts that information into a variable that you specify. You saw prompt() in the sample above.

Microsoft Internet Explorer (IE) has a setting that allows the user to prevent the prompt() function from working. If your prompt() window is not displaying, check this setting:

Here is a sample page that uses prompt(). (The code is shown below:)

<html>
<head>
<title>A Form Letter</title>
<script type="text/javascript">
<!-- hide me


var the_name = prompt("What's your name?", "put your name here");

// show me -->
</script>
</head>
<body>
<h1>Dear

<script type="text/javascript">
<!-- hide me

document.write(the_name);

// show me -->
</script>,</h1>

Thank you for coming to my Web page.

</body>
</html>

Built-In Objects

JavaScript is object-oriented. An object is a single unit or component that contains functions and variables. The functions in an object are called methods, and the variables in an object are called properties.

JavaScript has some built-in objects that programmers use often. One of these objects is the document object. The document object contains information (properties) about the Web page (document) that is currently displayed by the browser. The document object also contains some methods that you can use to modify the displayed document.

As I pointed out above, almost everything that you do in JavaScript involves an object, even if it does not appear to be so. But the object-based nature of JavaScript is clear when you use what is called a built-in object to accomplish a task.

Some of JavaScript's most commonly-used built-in objects are:

We will look at how these built-in objects are used as the class progresses. For now, look at this short example:

(And please note that the plus sign in the following example is the string concatenation operator. We will see this operator again next week.)

  <script type="text/javascript">
    var dateStuff = new Date();
    
    document.write("Today's date is " + dateStuff.toString());
  </script>

You can see this code running here.

Please note these additional points about the above code:


Variable Scope

Variable scope refers to where in your program code a variable can be used. The scope can be either global or local.

A global variable is one declared outside a function. It can be used anywhere in the code.

A local variable is one declared inside a function. It can only be used inside that function.

Please note that the parameters within the parentheses of a function definition are considered to be local variables inside the function.

Global variables can be very handy. But one rather interesting "feature" of Javascript is that even if you declare a variable inside a function but forget to use the keyword var when declaring it, it is mysteriously created as a global variable.

Here is some code that demonstrates this "feature":

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<html>
<head>
	<title>Declaring Variables</title>
  <script type="text/javascript">
    <!--
    function getNames()
    {
      the_name = prompt("What's your name?", "");
      dog_name = getDogName();
      alert(the_name + " has a dog named " + dog_name + ".");
    }
    
    function getDogName()
    {
      the_name = prompt("What is your dog's name?", "");
      return the_name;
    }
    
    function getNames2()
    {
      var the_name = prompt("What's your name?", "");
      var dog_name = getDogName2();
      alert(the_name + " has a dog named " + dog_name + ".");
    }

    function getDogName2()
    {
      var the_name = prompt("What is your dog's name?", "");
      return the_name;
    }
    //-->
  </script>
</head>

<body>

<div align="center">
<a href="#" target="_blank" onclick="getNames(); return false;">Click here for a survey.</a>
<br><br>
<a href="#" target="_blank" onclick="getNames2(); return false;">Click here for a better survey.</a>
</div>

</body>
</html>

You can see the above code running here.


Events

Events are one of the main ways that JavaScript can make your HTML pages dynamic and/or interactive. An event is a specific circumstance that JavaScript detects, such as a mouse click or a mouse rollover. Mouse clicks and mouse rollovers are called user events.

There are other types of events that JavaScript detects, though, such as the load event, which happens when the page being displayed has completely loaded into the browser.

Here is a list of the events that JavaScript monitors and detects:

Event Triggered (happens) When
abort The loading of an image is interrupted
blur An element, such as a radio button, becomes inactive
click An element is clicked once
change The value of an element changes
error There is an error when loading a document or image
focus An element becomes active
load A document or image loads
mouseout The mouse cursor moves off an element
mouseover The mouse cursor moves over an element
reset A form resets
select A user selects a field in a form
submit A user submits a form
unload A document unloads (closes)


Event Handlers

When an event occurs, your JavaScript code can respond to that event. JavaScript code that responds to an event is called an event handler.

Your event handler code is written as an attribute of the HTML tag that the event occurs in. The general syntax of an event handler is like this:

  <HTMLtag eventHandler="Some JavaScript Code">

Event handler names are the same as the name of the event itself, with a prefix of on. For example, the event name for the user's clicking a button element is onclick. Note that the name of the event handler is actually an HTML attribute.

In our example, the tag could be coded like this:

  <input type="button" 
         value="Click Me!"
         onclick="alert('You clicked the button!');">
And the above code looks like this when it is running.

You can put more than one JavaScript statement inside the value of the "event" attribute of a tag. Here is a sample of how to do that:

  <input type="button" 
         value="Click Me!"
         onclick="var yourAge = prompt('How old are you?', 'Your Age'); alert('Your age is ' + yourAge);">
And the above code looks like this when it is running.


HTML Tag Events

Various types of HTML tags have events associated with them. Here is an example of an <input> element in a form that responds to the blur event:

<html>
<head>
	<title>Blur Event</title>
</head>

<body onload="document.myForm.textButton.focus();">
<form name="myForm">
  <input type="text" value="default text"
         name="textButton" 
         onblur="alert(this.value);">
</form>
<br>
<h4>Click outside the text element, or use the Tab key...</h4>
</body>
</html>
You can see this code running here.

Please note these points about the above code:

Here is a list of the various types of HTML tags and their associated events:

Element Description Event(s)
<a>...</a> Link click
mouseover
mouseout
<img> Image abort
error
load
<area> Area click
mouseover
mouseout
<body>...</body> Document Body blur
error
focus
load
unload
<button>...</button> Button click
<frameset>...</frameset> Frameset blur
error
focus
load
unload
<frame> Frame blur
focus
<form>...</form> Form submit
reset
<input type="text"> Input Text Field blur
focus
change
select
<textarea>...</textarea> Text area blur
focus
change
select
<input type="submit"> Submit button click
<input type="reset"> Reset button click
<input type="button"> Generic button click
<input type="radio"> Radio button click
<input type="checkbox"> Checkbox click
<select>...</select> Selection (list box) blur
focus
change


Link Events

When a user clicks on a link, the browser automatically handles the click event and loads the file or document that is referenced in the "href" attribute of the <a> tag. But you can override the browser's handling of the click event with your own code.

In the event handler that you write for the onclick attribute of the <a> tag, you need to return a value to the browser to tell the browser what to do with its default handling of the click event. The two possible return values are:

return value what it tells the browser
true perform the default action of opening the URL in the "href" attribute
false do not perform the default action

Here is some code that uses the click event in an <a> tag:

<!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Click Event in Anchor Tag</title>
  <link rel="stylesheet" type="text/css" href="Samples.css">
  <script type="text/javascript">
    /* <![CDATA[ */
    function warnUser()
    {
      return confirm("This link is only for people with Golden Retrievers!\n\nClick 'Cancel' if you do not love Golden Retrievers.\n\nClick 'OK' if you love them.");
    }
    /* ]]> */
  </script>
</head>

<body>
  <div id="mainDiv">
	<p>
	<a href="GoldenRetrievers.html" onclick="return warnUser();">Golden Retriever Club Home Page</a>
	</p>
  </div>
</body>
</html>
The above code looks like this when it is running.

Please note these points about the above code:


[ Optional Section ]

Objects

JavaScript is an object-based programming language. This term is intended (by those who think that JavaScript is not a "real" programming language) to communicate the fact that JavaScript is not object-oriented. I regard this distinction as rather artificial, since you are dealing with objects in everything you do in JavaScript. I am comfortable referring to JavaScript as "object-oriented," too.

But the distinction does point up some important differences between JavaScript (which is an interpreted language) and compiled object-oriented languages such as C++ and Java. (The term "compiled" refers to the fact that these other languages require you to transform your program (its source code) into machine language so the computer can run it. The transformation process is called "compilation".)

In a compiled language such as C++ or Java:

In contrast, in an interpreted language such as JavaScript:

Custom JavaScript objects (objects that you create) are based on functions called constructor functions. In other words, a constructor function is a function that is used to create an object. When you create an object with a constructor function, the object contains, or inherits, all of the properties and methods that the constructor function contains.

An example of a constructor function follows:

  function Animal(type, sound, transport_mode)
  {
    this.animal_type = type;
    this.animal_sound = sound;
    this.animal_transport_mode = transport_mode;
  }
Please note these points about the above code:

Objects are created from constructor functions with the new keyword. The following code sample creates a new object called pet from our Animal() constructor function:

  pet = new Animal("dog", "woof", "walk/run");
Please note these points about the above code:

An example of some code that uses the Animal object is below, in the "Methods" section of this handout.


[ Optional Section ]

Methods

As I pointed out above, a method is a function that is contained in an object. In a manner similar to how you use it to code properties in a custom function, you use the this keyword to code references to those properties in a custom method.

Here is an example of a method that you could add to the Animal custom object's constructor function:

  function displayAnimalProperties()
  {
    document.write("Type: " + this.animal_type + "<br>");
    document.write("Sound: " + this.animal_sound + "<br>");
    document.write("Mode: " + this.animal_transport_mode + "<br>");
  }

In order to add the above code to the Animal object, you need to add another line to the object's constructor function, too. You would need to add the following line to the Animal constructor:

  this.displayAnimalProperties = displayAnimalProperties;

Please note these points about the above two segments of code:

Here is some code that uses the displayAnimalProperties() method:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
	<title>A Custom Object -- Animal</title>
  <script type="text/javascript">
    function displayAnimalProperties()
    {
      document.write("Type: " + this.animal_type + "<br>");
      document.write("Sound: " + this.animal_sound + "<br>");
      document.write("Mode: " + this.animal_transport_mode + "<br>");
    }

    function Animal(type, sound, transport_mode)
    {
      this.animal_type = type;
      this.animal_sound = sound;
      this.animal_transport_mode = transport_mode;
      this.displayAnimalProperties = displayAnimalProperties;
    }
  </script>
</head>

<body>
<script type="text/javascript">
  var myAnimal = new Animal();
  myAnimal.animal_type = "fish";
  myAnimal.animal_sound = "blub";
  myAnimal.animal_transport_mode = "swim";
  
  myAnimal.displayAnimalProperties();
</script>
</body>
</html>

You can see the above code running here.

Please note these points about the sample code that the above link displays:


[ Optional Section ]

Inheritance and Prototypes

Objects inherit, or, contain, the properties and methods that are defined in the constructor functions from which they are instantiated. After you instantiate an object, you can assign additional properties to the object, using a period. Look at this code sample:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
	<title>Adding a Property to an Object</title>
  <script type="text/javascript">
    function Animal(type, sound, transport_mode)
    {
      this.animal_type = type;
      this.animal_sound = sound;
      this.animal_transport_mode = transport_mode;
    }
  </script>
</head>

<body>
<script type="text/javascript">
  var cat = new Animal("feline", "meow", "walk/run");
  cat.size = "fat";
  document.write(cat.size);
</script>
</body>
</html>
You can see the above code running here.

Please note these points about the above code:

The prototype property is a built-in property that adds a property to an object's constructor function from code that is not actually in the constructor function. Here is some code that adds the size property to the Animal constructor function:

  cat = new Animal("feline", "meow", "walk/run");
  Animal.prototype.size = "fat";

Any code that follows the code sample shown above, after a new object is created from the Animal constructor function, of course, will be able to use the size property of the new Animal object.

One problem with the above code is that any objects created with the Animal constructor after you have added the size property will have the value "fat", which is probably not what you want. Here is some better code:

  cat = new Animal("feline", "meow", "walk/run");
  Animal.prototype.size = "";
  cat.size = "fat";
  
  horse = new Animal("equine", "neigh", "walk/canter/gallop");
  horse.size = "huge";

You can use the prototype property to add methods to an object definition, also. To extend an object definition with a new method, you use the prototype property, followed by the new keyword and the name of the new constructor that you have made.

Here is some code that shows how to extend an object definition with a new method, using the prototype property:

  function Animal(type, sound, transport_mode)
  {
    this.animal_type = type;
    this.animal_sound = sound;
    this.animal_transport_mode = transport_mode;
  }
  
  function WildAnimal(home, food)
  {
    this.habitat = home;
    this.diet = food;
  }
  
  WildAnimal.prototype = new Animal();
  
  function FarmAnimal(classification, residence)
  {
    this.food_group = classification;
    this.location = residence;
  }
  
  FarmAnimal.prototype = new Animal();

Objects instantiated from either WildAnimal or FarmAnimal will include the three properties from the Animal constructor function, along with the properties specific to each individual object (WildAnimal or FarmAnimal, that is).

The following code instantiates an object from FarmAnimal and assigns all of the properties:

  var chicken = new FarmAnimal();
  chicken.animal_type = "chicken";
  chicken.animal_sound = "cluck";
  chicken.animal_transport_mode = "walk/fly";
  chicken.location = "barnyard";
  chicken.food_group = "poultry";
OR
  var horse = new FarmAnimal("dogfood","barnyard/field");
  horse.animal_type = ""equine";
  horse.animal_sound = "neigh";
  horse.animal_transport_mode = "walk/canter/gallop";

You can see the above code in a complete HTML page below:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
	<title>Prototyped Methods</title>
  <script type="text/javascript">
  function Animal(type, sound, transport_mode)
  {
    this.animal_type = type;
    this.animal_sound = sound;
    this.animal_transport_mode = transport_mode;
  }
  
  function WildAnimal(home, food)
  {
    this.habitat = home;
    this.diet = food;
  }
  
  WildAnimal.prototype = new Animal();
  
  function FarmAnimal(classification, residence)
  {
    this.food_group = classification;
    this.location = residence;
  }
  
  FarmAnimal.prototype = new Animal();

  var chicken = new FarmAnimal();
  chicken.animal_type = "chicken";
  chicken.animal_sound = "cluck";
  chicken.animal_transport_mode = "walk/fly";
  chicken.location = "barnyard";
  chicken.food_group = "poultry";

  var horse = new FarmAnimal("dogfood","barnyard/field");
  horse.animal_type = "equine";
  horse.animal_sound = "neigh";
  horse.animal_transport_mode = "walk/canter/gallop";
  </script>
</head>

<body>
<h4>A horse makes the sound
<script type="text/javascript">
  document.write('"' + horse.animal_sound + '".');
</script>
</h4>
<h4>A horse hangs out in the
<script type="text/javascript">
  document.write(horse.location);
  document.write(".");
</script>
</h4>
</body>
</html>

You can see the above code running here.


[ Optional Section ]

Image Maps

Okay, you should now know enough about events and event handlers to understand the image map sample that we looked at last week. Here is the code:

<html>
<head>
  <title>North America</title>
  <script type="text/javascript">
    <!-- HIDE FROM INCOMPATIBLE BROWSERS
    function change_image(image_name) {
         document.northAmerica.src = image_name;
    }
    function reset_image() {
         document.northAmerica.src = "north_america.gif";
    }
    // STOP HIDING FROM INCOMPATIBLE BROWSERS -->
  </script>
</head>
<body>
  <img src="north_america.gif" usemap="#northAmerica_map" name="northAmerica">
<map name="northAmerica_map">
<area shape="circle" coords="44,46,20" nohref onmouseover="change_image('alaska.gif'); return false" onmouseout="reset_image(); return false">
<area shape="poly" coords="110,10,144,22,152,60,107,31" nohref onmouseover="change_image('greenland.gif'); return false" onmouseout="reset_image(); return false">
<area shape="poly" coords="62,45,107,23,162,86,125,111,106,100,55,96,49,64" nohref onmouseover="change_image('canada.gif'); return false" onmouseout="reset_image(); return false">
<area shape="poly" coords="60,96,125,105,142,98,134,153,97,155,50,123" nohref onmouseover="change_image('continental_us.gif'); return false" onmouseout="reset_image(); return false">
<area shape="poly" coords="61,135,122,165,109,181,65,159,60,136" nohref onmouseover="change_image('mexico.gif'); return false" onmouseout="reset_image(); return false">
</map>
</body>
</html>

You can see the above code running here.

Please note these points about the image map code sample:


[ Optional Section ]

An Alternative to document.write()

So far, a lot of the sample pages in these handouts have used the document.write() built-in method to put JavaScript-generated information into the Web page's display.

There is a major problem, though, with using document.write(): If you use this method after the page has loaded, all of the page's code -- ALL OF IT -- including the HTML tags and any other JavaScript code -- gets wiped out and replaced with only what is written into the page with document.write() after the page has loaded.

Fortunately, there are some alternatives to using document.write(). We will see one of them much later in the course when we talk about jQuery events and effects. And we will see another alternative right now: The innerHTML property, along with the document.getElementById() method.

The innerHTML Property

JavaScript provides a lot of properties about the Web page, which we can use to change what is in the page after the page has loaded. The main property that is used for this purpose is innerHTML.

The document.getElementById() Method

And along with the innerHTML property, JavaScript provides an extremely handy built-in function called document.getElementById(). This method is used to get a "handle" (actually, an object) to any HTML tag which has an id attribute in it.


This powerful combination of method and property is used like this:

  1. Get or build a string value so it has the desired new contents for the HTML tag that you want to change. You can even put HTML tags into this string value that you are building.
  2. Assign the value of your string to the HTML tag that you want to change, using the "handle" to the HTML tag which document.getElementById() provides to you.

Here is a sample page which shows how you can use this combination of method and property. This is page ComboSample.html:

<!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Powerful Method and Property Combo</title>
  <link rel="stylesheet" type="text/css" href="Samples.css">
  <script type="text/javascript">
    /* <![CDATA[ */
    function showStuff(newContentsString)
    {
      document.getElementById("newContentsDiv").innerHTML = newContentsString;
    }
    /* ]]> */
  </script>
</head>

<body onload="showStuff('<h3>The page has loaded!</h3>');">
  <div id="mainDiv">
    <div id="newContentsDiv">
    </div>
    <button onclick="showStuff('<h3>You just clicked a button!</h3>');">Click this Button</button>
    <button onclick="showStuff('<h3>You just clicked another button!</h3>');">Click this Button, too</button>
  </div>
</body>
</html>

You can see the above code running in a browser here.