Notes - Tom Kleen

advertisement
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
Add a button to your HTML body:
<form>
<button type="button" onclick="doSomething()">Click Me!</button>
</form>
Then create a <script> element in the head of the HTML file.
Add the following: It creates an object variable called student that has two properties (tests
and homework) and one method (average()).
function doSomething()
{
var student = {
tests:100,
homework:90,
average: function() { return this.tests *.50 + this.homework * .50;}
};
console.log("Student average should be 95: " + student.average());
}
Save the HTML file.
Load it into your browser and press F12 to open the Developer Tools.
Click on the Click Me! button. The doSomething() function should get executed and the
output of the console.log method should appear in the Console window of the Developer
Tools.
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
Document1
1
2/9/2016
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
Add the following to your <script> element:
function f(x, y, z)
{
if (arguments.length !== 3)
alert("Not enough arguments!");
else
alert("Correct number of arguments");
}
And add the following to the end of your doSomething() method:
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
Add the following code to your <script> object.
function max()
{
var big = arguments[0];
for (i = 1; i < arguments.length; i++)
if (arguments[i] > big)
big = arguments[i];
return big;
}
Add the following to your doSomething() method:
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
The function works like this:
alert("JavaScript is fun!");
Example
Replace the console.log methods in doSomething with:
Document1
2
2/9/2016
alert("Max should be 4: " + max(1, 2, 3, 4);
alert("Max should be 1000: " + max(1, 2, 3, 4, 1000, 900, 800, 700, 600);
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
Add the following to your <script> element:
function getName()
{
do
{
var name = prompt("What is your name?");
}
while (!name);
alert("Hello, " + name);
return name;
}
Add the following to the end of your doSomething() method:
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
Add the following to your <script> element:
function getName2()
{
do
{
var name = prompt("What is your name?");
var correct = confirm("You entered " + name + ". Is this OK?");
}
while (!correct);
alert("Hello, " + name);
return name;
}
Add the following to the end of your doSomething() method:
getName2();
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.
Document1
3
2/9/2016
Example
Add to the end of your doSomething() method:
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.
Add the following to the body of your HTML file.
<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 events 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 word.
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.
Document1
4
2/9/2016
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 http://gregmurray.org/ipad/touch-events.html for 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.
Document1
5
2/9/2016
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")
a. A division within the form ("inputSection")
i. a label that is attached to the input box
ii. an input box of type search
b. Another division within the form ("buttonSection")
i. a button (set its id to "search")
ii. a button (set its id to "getAllContacts")
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": "john@briarcliff.edu" },
{"name": "Paul", "email": "paul@briarcliff.edu" },
{"name": "George", "email": "george@briarcliff.edu" },
{"name": "Ringo", "email": "ringo@briarcliff.edu" },
{"name": "Larry", "email": "larry@briarcliff.edu" },
{"name": "Moe", "email": "moe@briarcliff.edu" },
{"name": "Curly", "email": "curly@briarcliff.edu" }
]
};
Document1
6
2/9/2016
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.
2.
3.
4.
5.
Print
Print
Print
Print
Print
the contacts object to the console.
the addressBook object to the console.
the addressBook.length to the console.
each element of the addressBook to the console.
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 getAllContacts:
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.
Document1
7
2/9/2016
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.
Document1
8
2/9/2016
Download