JavaScript, Day 4

Create a new HTML5 project called Page16JS04.html. Add a pair of <script</script> tags.

Methods

A method is a JavaScript function that is stored in a property of an object.

Example

The following creates an object variable called student that has two properties (tests and homework) and one method (average()).

var student = {

tests:100,

homework:90,

average: function() { return this.tests *.50 + this.homework * .50;}

}

console.log("Student average should be 95: " + student.average());

Note that without the keyword this the function does not work.

Optional Arguments

A function may be called with more arguments than declared parameters or with fewer arguments than declared parameters.

If fewer arguments are passed to the function, the unmatched parameters are given the value undefined.

If extra arguments are passed to the function, the additional arguments cannot be accessed by name. However, they become part of the function's arguments object. Every function has an arguments object that behaves like a zero-based array (although technically, it's not an array). The first argument can be accessed through arguments[0], the second argument through arguments[1], etc. The arguments object also has a length property that can be used to determine the number of elements in the argument list.

Example

function f(x, y, z)

{

if (arguments.length !== 3)

alert("Not enough arguments!");

else

alert("Correct number of arguments");

}

f(1, 2);

f(1, 2, 3);

One use of the arguments list is to allow functions that will accept an arbitrary number of elements.

Example

function max()

{

var big = arguments[0];

for (i = 1; i < arguments.length; i++)

if (arguments[i] > big)

big = arguments[i];

return big;

}

console.log("Max should be 4: " + max(1, 2, 3, 4));

console.log("Max should be 1000: " +

max(1, 2, 3, 4, 1000, 900, 800, 700, 600));

Producing Output

There are a number of ways to get output from a JavaScript program.

The alert() method

An alert box will display a message on the screen and wait for the user to close it.

Example

alert("JavaScript is fun!");

The prompt() method

The prompt() method displays a message and waits for the user to enter a string. It's similar to an input box in Windows.

Example

function getName()

{

do

{

var name = prompt("What is your name?");

}

while (!name);

alert("Hello, " + name);

return name;

}

console.log(getName());

The confirm() method

The confirm() method displays a message and waits for the user to click either an OK button or a Cancel button.

Example

function getName()

{

do

{

var name = prompt("What is your name?");

var correct = confirm("You entered " + name + ". Is this OK?");

}

while (!correct);

alert("Hello, " + name);

return name;

}

The console.log() method

Use console.log to write output to the console (only visible when you press the F12 key). This is mostly for debugging.

Example

console.log ("Hello!");

The document.write() method

The document.write() method will write text into the middle of your HTML document. document.write() statements in the body will cause the text to be written to the page. document.write() statements that are in the head will only write to the page when the function in which they reside gets executed.

Example

document.write("Hello!");

The getElementById() method

JavaScript is often used to manipulate the HTML on a page. To access an HTML element from JavaScript, you can use the document.getElementById(id) method, where id is a name that you have assigned to an element using the id attribute.

Example (w3)

The following example shows how the My First Paragraph text never appears! NOTE: The <script> tag must follow the <p> tag.

<h1>My First Web Page</h1>

<p id="demo">My First Paragraph</p>

<script>

// Shows use of getElementById and innerHTML

document.getElementById("demo").innerHTML="My First JavaScript";

</script>

JavaScript Events

Events

An event is a signal that is generated by the computer when some specific action occurs. Users frequently cause events to occur, but event may occur that are not initiated by the user. For example, a "load" event is fired when a page is first loaded. And although a user technically caused the page to be loaded, the connection is less direct than clicking on a hyperlink, for example. Perhaps the most common event is the click event that occurs whenever a mouse is clicked. Note that event names are all lower-case, even when the event name is more than one work.

These events need to be attached to DOM elements to be executed. The statement “click a link” means that the event “click” is being attached to a “link,” and then a function is executed. We will attach events to DOM elements in the element tags.

Common events

click

Occurs when the user clicks on a link or form element.

mouseover

Occurs when the user moves the mouse over an HTML element.

focus

Occurs when input focus (the cursor) is given to a form element.

blur

Occurs when the input focus is removed from a form element.

change

Occurs when the value of a form field is changed by the user.

load

Occurs when a page is loaded into the browser.

unload

Occurs when the user leaves a page.

submit

Occurs when the user clicks on a submit button.

select

Occurs when the user selects a form element's field.

touch events: touchstart, touchend, touchmove

See an example.

Event Handlers

An event handler is a function that gets executed in response to a given event. Although it is possible to write an event handler inside of an HTML tag, it is better to put the event handler function in a script block, usually in the head element.

An event handler has the same name as the event that it is supposed to respond to, but with the word "on" at the beginning. To indicate the name of the function that is supposed to respond to an element's click event, the keyword onclick is used.

Event handlers are often used to respond to events that occur in a form.

Example

We are going to look at a relatively simple example that will respond to click events, read input from the user, and modify the DOM in response to the user.

We are going to write a simple program that will look up a user's email address for us. We are not going to get the data from a file (which would be much more realistic). We are going to build the data into our JS program.

Let's build the web page. It should look like this:

Create the HTML

The HTML5 elements above are:

  1. h1
  2. A form ("search-form")
  3. A division within the form ("input-section")
  4. a label that is attached to the input box
  5. an input box of type search
  6. Another division within the form ("button-section")
  7. a button
  8. a button

Add CSS

Add some CSS styling rules:

  1. Make the text in both divisions 18 pixels tall.
  2. Make the buttons 150 pixels wide by 40 pixels tall.
  3. Add a 10 pixel margin around each division.

Add data

We are going to build the data into our program. Copy the following to the top of your script.

var contacts = {

"addressBook":

[

{"name": "John", "email": "" },

{"name": "Paul", "email": "" },

{"name": "George", "email": "" },

{"name": "Ringo", "email": "" },

{"name": "Larry", "email": "" },

{"name": "Moe", "email": "" },

{"name": "Curly", "email": }

]

};

This says that the variable contacts is an object with one property named addressBook. The value of the addressBook property is an array of objects. Each object has a name property and an email property.

contacts refers to the entire object.

addressBook refers to the array.

addressBook.length refers to the size of the array.

addressBook[i] refers to an element of the array (one name and email address—assuming i is defined).

addressBook[i].name refers to a single name.

addressBook[i].email refers to a single email address.

Write code to:

  1. Print the contacts object to the console.
  2. Print the addressBook object to the console.
  3. Print the addressBook.length to the console.
  4. Print each element of the addressBook to the console.
  5. Print each name and email in the addressBook to the console.

Produce output by modifying the DOM

The Get all contacts button

We want to produce output on the page when the user clicks on a button. When the user clicks on the Get all contacts button, we want to display all of the contacts in the web page.

First we need a place to put it. Add a <div> element to the bottom of your HTML. Give it an id of output.

We need a function that will display all of the entries in the address list. Create a function called getAllContacts().

function getAllContacts()

{

}

Add an onclick attribute to the get-all-button:

onclick="getAllContacts();"

Run the program and click on the Get all contacts button. We can't really tell if we are getting to the function. We need to add some debugging code. Add an alert message:

alert("In getAllContacts");

We need to step through the array of names and email addresses one at a time and retrieve each name and address. After we retrieve it, we want to put it in the output div. First, write the code to step through the array, retrieving each name and address. Use either console.log or alert to verify that you are getting the data correctly.

When you are sure that you are getting the data correctly, you can put the info into the inner HTML of the output div. Try it. Create a paragraph for each entry in the array.

The Search button

We also need to look up a single name and email address. When the user clicks on the Search button, we need to find all matches in the "database". We will use the same <div> element with the id output.

We need a function that will find all matches in the address list. Create a function called search().

function search()

{

}

Add an onclick attribute to the search-button:

onclick="search();"

Again, add an alert message to the search function to make sure that you are actually calling it. We need to step through the array of names and email addresses and find all that match the given search string. Check out the indexOf string method.

Since string matches use a case-sensitive comparison, we should probably modify our lookup so that it matches regardless of the case of the letters.

Day16-JavaScript04.docx110/11/2018