Title: Introduction to JavaScript
1Introduction to JavaScript
- What is JavaScript?
- How does it work?
- What can it do?
- How do you use it?
- Conditionals and Loops
- Summary
2Introduction to JavaScript
- JavaScript is the programming language of the
Web! - JavaScript can react and add life to your pages,
it can be programmed to do what you want. - HTML is simply a 'markup language'. It just
shows stuff. - In these JavaScript lessons you will learn how to
write JavaScripts and insert them into your HTML
documents, and how to make your pages more
dynamic and interactive.
3Introduction to JavaScript
- JavaScript Examples
- There are many interesting things that you can do
with JavaScript, and many free scripts that you
can use and adapt for your own pages. - Before getting started on this tutorial, go to
http//javascript.internet.com and see some
examples of how you can use JavaScript on your
web pages!
4Introduction to JavaScript
- What is JavaScript?
- JavaScript is a scripting language
- A scripting language is a lightweight
programming language (not a markup language,
like HTML) - A JavaScript is lines of executable computer
code - JavaScript can be inserted into an HTML page
- JavaScript is an open scripting language that
anyone can use without buying a license - JavaScript is supported by all major browsers
like Netscape and Internet Explorer
5Introduction to JavaScript
- How Does it Work?
- When a JavaScript is inserted into an HTML
document, the Internet browser will read the HTML
and interpret the JavaScript. - The JavaScript can be executed immediately or at
a later event, like when someone clicks a button.
6Introduction to JavaScript
- What can JavaScript Do?
- JavaScript gives HTML designers a programming
tool - JavaScript can put dynamic text into an HTML page
- JavaScript can react to events
- JavaScript can read and write HTML elements
- JavaScript can be used to validate data
7Introduction to JavaScriptWhat can a JavaScript
Do?
- JavaScript gives HTML designers a programming
tool - HTML authors are normally not programmers, but
JavaScript is a very light programming language
with a very simple syntax! - Almost anyone can start putting small chunks of
JavaScript code into their HTML documents. - These scripts can perform calculations, change
your site based on the user's selections, and
more!
8Introduction to JavaScriptWhat can a JavaScript
Do?
- JavaScript can put dynamic text into an HTML
page - A JavaScript statement like this
- document.write("" name "")
- can write a variable name into the display of an
HTML page, instead of this static HTML text - Bill Gates
9Introduction to JavaScriptWhat can a JavaScript
Do?
- JavaScript can react to events
- A JavaScript can be set to execute when something
happens, like when a page has finished loading or
when a user clicks on an HTML element. - These are called 'eventHandlers'. There are many
of them, and many are premade for you.
10Introduction to JavaScriptWhat can a JavaScript
Do?
- JavaScript can read and write HTML elements
- A JavaScript can read an HTML element and change
the content of an HTML element, like a text box,
image source or label. - Have you ever seen an image change when the mouse
moves over it? That's one example.
11Introduction to JavaScript
- How to Put a JavaScript Into an HTML Document
- To insert a script in an HTML document, use the
tag. Use the language attribute to
define the scripting language. - The following slide shows an example
12Introduction to JavaScriptPutting JavaScript
into an HTML Document
-
-
-
-
-
-
-
-
- The next slides take you through the steps to
write this file.
13Introduction to JavaScriptPutting JavaScript
into an HTML Document
-
- .
-
- Start by writing the tags.
- The tags must name the
scripting language. These tags tell the browser
that the language"JavaScript". - If the browser doesn't know the language that
you're using, it may not be able to interpret it.
14Introduction to JavaScriptPutting JavaScript
into an HTML Document
-
-
-
- Next step add the comment tags. Why?
- Some older browsers cant handle JavaScript.
(Some people still use AOL 1.0). If you wrap
the script with HTML tags, older browsers ignore
the script and your web page doesn't break.
15Introduction to JavaScriptPutting JavaScript
into an HTML Document
-
-
-
- You may know that are HTML comment
tags. Notice that the ending tag is not -- but
// --. - // is one way to include comments in JavaScript!
You must use JavaScript comments to comment out
the HTML comment. - If confused, just be sure to put these comment
marks in your code.
16Introduction to JavaScriptPutting JavaScript
into an HTML Document
-
-
-
- document.write(Hello World!) is the syntax to
write on a web page (document). This writes
Hello World!, and nothing else. - You'll learn more about document.write later,
this is just a basic JavaScript example.
17Introduction to JavaScriptPutting JavaScript
into an HTML Document
- Activity 1
- Try to create your first HTML file with
JavaScript. Simply use the document.write as
described in this presentation. - Save the file as js1.html, and test it.
18Introduction to JavaScript
- Where to Put the JavaScript
- JavaScripts placed in the body of a page will be
executed as soon as the page loads into the
browser. - This is not always what we want. Sometimes we
want to execute a script when a page loads, other
times when a user triggers an event. - Where you place the JavaScript on a page is
important regarding how soon it acts.
19Introduction to JavaScriptWhere to Put the
JavaScript
- Scripts in the head section
- Scripts to be executed only when they are called
go in the head section (between the and
tags). - When you place a script in the head section, you
will ensure that the script is loaded before
anyone uses it, for faster performance. - When you need it, it's ready for you in the
section of your page!
20Introduction to JavaScriptWhere to Put the
JavaScript
- Scripts in the head section
- You may recall in our Forms lesson, we called a
JavaScript "checkUsername" using the form
'action'. - Most likely this JavaScript was located in the
of the web page, as it is a function that
we call, it's not automatic.
21Introduction to JavaScriptWhere to Put the
JavaScript
- Scripts in the body section
- Scripts to be executed immediately when the page
loads go in the body section. - When you place a script in the body section it
generates the content of the page. - You dont have to choose between putting scripts
in the head or body section. Put as many as
youd like in both or either one!
22Introduction to JavaScriptWhere to Put the
JavaScript
- Scripts in the body section
- A very common JavaScript to be located in the
body section of a web page for automatic loading
is one that displays the date and time. - While it won't look very pretty, try putting this
simple date and time JavaScript in the body of a
web page (we'll explain it later) -
- document.write(new Date())
23Introduction to JavaScriptWhere to Put the
JavaScript
- External JavaScript Files
- Sometimes you might want to run the same script
on several pages, without writing the script on
each and every page. - To simplify this you can write a script in an
external file, and save it with a .js file
extension. - This is done frequently when working in web
development teams, where one person writes the
JavaScript while another makes the web pages.
24Introduction to JavaScriptWhere to Put the
JavaScript
- External JavaScript Files, cont'd
- First, write the following line in Notepad (yes,
only the next line) - document.write("This script is in an external
file.") - Save the file as bodywriter.js.
- Note The external script cannot contain the
tag.
25Introduction to JavaScriptWhere to Put the
JavaScript
- External JavaScript Files, cont'd
- You also need to write the following HTML page in
Notepad. Name it whatever you want, but be sure
to save it in the same place as the
"bodywriter.js" file. -
-
-
-
-
26Introduction to JavaScriptWhere to Put the
JavaScript
- External JavaScript Files, cont'd
-
-
-
-
-
-
- The src tag in your tag calls the
external JavaScript. Because bodywriter.js is an
external file, any web page on your site can call
it!
27Introduction to JavaScriptWhere to Put the
JavaScript
- Summary
- At this point, you should know that JavaScript
adds more interactive and dynamic behaviors to
your web pages. - In addition, you should know that it can go into
one of three locations , , or an
external file.
28Introduction to JavaScriptWhere to Put the
JavaScript
- Activity 2
- Go to http//javascript.internet.com and take a
look at all of the free JavaScripts offered. - Follow their instructions to use one of them
successfully. In addition, save the JavaScript
in an external file. Save your HTML file as
borrowedjs.html, and save the external file as
source.js. - This should give you an idea of what
JavaScripting can do for you!
29Introduction to JavaScript
- JavaScript EventHandlers
- JavaScript has some pre-made 'functions' called
EventHandlers. - These are built-in shortcuts to make your page
more dynamic. This section will discuss these
popular tools, and review the more common ones. - You will then try implementing them yourself on a
web page.
30Introduction to JavaScriptJavaScript
EventHandlers
- What is an "event"?
- When the user does something on a web page like
clicking the mouse, moving the mouse, leaving the
page, etc., these are all events. - For just about every event, there is an
eventHandler. - An eventHandler is usually associated with an
object like a button, link, window, etc., and it
reacts to events dealing with that object.
31Introduction to JavaScriptJavaScript
EventHandlers
- eventHandlers
- As mentioned on the previous slide, an
eventHandler is usually associated with an object
like a button, link, window, etc., and it reacts
to events dealing with that object. - You will usually recognize an eventHandler by the
name. Most of them start with the word "on",
then something more descriptive. - The first one you will see is called "onClick".
32Introduction to JavaScriptJavaScript
EventHandlers
- onClick
- onClick executes JavaScript code when a Click
event occurs that is, when an object on a form
is clicked. (Keep in mind, a Click event is a
combination of the MouseDown event and MouseUp
event). - onClick can be used on following objects
- Button, document, Checkbox, Link, Radio, Reset,
Submit
33Introduction to JavaScriptJavaScript
EventHandlers
- onClick example
- To use onClick, simply put it inside the tag of
an appropriate HTML object, like this - confirm('Go to CNN.com?')"CNN
- Copy this code into an HTML document to see what
onClick does.
34Introduction to JavaScriptJavaScript
EventHandlers
- onMouseOver
- onMouseOver is one of the most popular
eventHandlers. - It executes JavaScript code when a MouseOver
event occurs that is, once each time the mouse
pointer moves over an object or area from outside
that object or area. - This can be used for pictures, links, and layers.
Usually, it calls a function when the mouse
moves over a certain area.
35Introduction to JavaScriptJavaScript
EventHandlers
- onMouseOver example
- Open a new HTML document, and paste the following
lines of code into it. Save it as mouseover.html
and test it! - Example one Background color change using
onMouseOver. - He
llo - Example two Alert box popup using onMouseOver
- there!')"Hello
36Introduction to JavaScriptJavaScript
EventHandlers
- onMouseOut
- onMouseOut is the opposite of onMouseOver when
you move the mouse out of a certain area, this
eventHandler is called. - For example, let's adjust Example One from the
last page. Replace the first line of code with
this, and save the file as mouseover2.html. Test
it by putting your mouseover the links. - onMouseOut"document.bgColor'whi
te'"Hello
37Introduction to JavaScriptJavaScript
EventHandlers
- Other EventHandlers
- There are many, many other eventHandlers that
handle closing windows, mouse movement, etc.
There are even eventHandlers for when you leave
their page! - Some other eventHandlers that you should
consider onLoad, onSubmit, onResize.
38Introduction to JavaScriptJavaScript
EventHandlers
- Other EventHandlers
- For an extensive list of JavaScript
EventHandlers, go to Netscape, the creators of
JavaScript, at - http//developer.netscape.com/docs/manuals/communi
cator/jsref/evnt.htm
39Introduction to JavaScriptJavaScript
EventHandlers
- Activity 3
- Demonstrate two eventHandlers. One popular use
is switching a picture using onMouseover and
onMouseout. Another popular use is starting a
clock using onLoad. - Be sure to explain what the eventHandler is
supposed to do on your web page. Name the page
eventhandlers.html.
40Introduction to JavaScript
- JavaScript Variables
- A variable is a "container" for information you
want to store, just like in algebra. You can use
these in your JavaScripts. - A variable's value can change during the script.
You can refer to a variable by name to see its
value or to change its value. - To really use JavaScript effectively, you have to
understand how it uses variables in its code.
41Introduction to JavaScriptJavaScript Variables
- Declare a Variable
- You can create a variable with the var statement
- var count
- The line above declares the variable count,
creating it for use later on. - (Hint The var word is optional, but its a
good habit to use it, so you know where it
originates.)
42Introduction to JavaScriptJavaScript Variables
- Assign a Value to a Variable
- You can assign a value to a variable once it is
created - count 3
- The line above assigns it a value equal to 3.
43Introduction to JavaScriptJavaScript Variables
- Declare a variable and assign a value to it
- You can both declare a variable AND assign it a
value in the same line, if you'd like - var count 3
- The line above declares the variable 'count' and
assigns it a value equal to 3.
44Introduction to JavaScriptJavaScript Variables
- Have the user assign a value to a variable
- If you design an HTML page with a form, the user
can input a value, and JavaScript can help you to
retrieve it. - For example, assume you have a form that asks for
the user to input their first name. You may want
to store this value from the user into a
variable. - How is this done?
45Introduction to JavaScriptJavaScript Variables
- Have the user assign a value to a variable,
cont'd - Before retrieving the value from the user, some
elements need to be known to the JavaScript - The form name, the field name, and the variable
name in which the retrieved value will be stored. - Assume for now that the HTML form is "loginForm",
the first name field is named "first", and the
variable is called "username".
46Introduction to JavaScriptJavaScript Variables
- Have the user assign a value to a variable,
cont'd - To retrieve the value from a form field, use this
statement - document.form name.field name.value
- In our case, we should use the names of our form
- document.loginForm.first.value
47Introduction to JavaScriptJavaScript Variables
- Have the user assign a value to a variable,
cont'd - To assign the value from a form field to a
variable, we simply use the "assignment
operator" - username document.loginForm.first.value
- We can now use the name supplied by the user for
our JavaScript.
48Introduction to JavaScriptJavaScript Variables
- Have the user assign a value to a variable,
cont'd - username document.loginForm.first.value
- A tip on reading the variable assignment
- Read the variable assignment from right to left,
and it may make more sense. For example - Take the "value" of the "first" field on the
"loginForm" of the document, and assign it to the
variable "username".
49Introduction to JavaScriptJavaScript Variables
- Using a variable to set the value of a field
- To reverse our process from before, you can also
use a variable and send its value to a form on a
field. - Assume we have another text field on our form
called "result". To send our variable "username"
into that field, we just reverse the assigning
code from our previous example - document.loginForm.result.value username
50Introduction to JavaScriptJavaScript Variables
- Using a variable to set the value of a field
- Evaluate the file takeandshow.html. This file
performs the actions just presented in this
slide, using the onClick eventHandler. - You won't understand all of the code in the
tags yet, but try to understand the way
the page retrieves then sets the name of the user
between the text fields. - The onClick will be discussed in more detail
shortly.
51Introduction to JavaScript
- JavaScript Functions
- This is not the last section of JavaScript, but
this is the final section of JavaScript before
you start writing your own scripts! - You will review what a 'function' is, and how to
write a basic one. - Combined with your knowledge of where to put
JavaScripts, you will soon write your own
JavaScript from scratch, and most of what you
have learned so far will now come together.
52Introduction to JavaScriptJavaScript Functions
- The most basic definition of a function is that
it's a bunch of code does something. - More formally, a function is a set of statements.
These statements combine to perform a certain
task. - A good function is simple and reusable.
53Introduction to JavaScriptJavaScript Functions
- How to Define a Function
- To create a function you define its name, any
values ("arguments"), and some statements - function functionName(argument1,argument2,etc)
-
- some statements
-
- These parts will be addressed one at a time.
54Introduction to JavaScriptJavaScript Functions
- How to Name a Function
- function functionName(argument1,argument2,etc)
-
- some statements
-
- The function name must start with a letter or
underscore, should not contain spaces or other
characters. Start the name with a small letter,
and capitalize additional words. - Make the name reflect the job of the function.
55Introduction to JavaScriptJavaScript Functions
- How to Name a Function
- Give the function a name that reflects its job.
- Some examples of function names
- myCalculator
- newSchoolCalendar
- addTwoNumbers
- _thisFunctionWorks
56Introduction to JavaScriptJavaScript Functions
- Function Arguments
- function functionName(argument1,argument2,etc)
-
- some statements
-
- Arguments are values you give to the function,
and the function works with them. If your
function added two numbers and gave you the
answer, the arguments would be the two numbers to
be added.
57Introduction to JavaScriptJavaScript Functions
- Function Arguments
- Functions can take many arguments, or no
arguments at all. - Just remember that arguments are simply pieces of
information that you are giving to the function. - Arguments are sometimes called parameters, so
don't worry if you ever see that word.
58Introduction to JavaScriptJavaScript Functions
- Function Statements
- function functionName(argument1,argument2,etc)
-
- some statements
-
- Between the curly braces are the statements that
do the actual work in the function. For example,
these would be the lines that can add two
numbers, or do some type of calculation before
returning a value. - The name of the function should describe what the
statements do.
59Introduction to JavaScriptJavaScript Functions
- Function Syntax
- First of all, the word 'syntax'. This is really
just a word that means the 'grammar and
punctuation' of a computer language. - JavaScript has its own syntax, as do most
languages. Many of them overlap though, so you
usually learn other ones fast!
60Introduction to JavaScriptJavaScript Functions
- Function Syntax
- function functionName(argument1,argument2,etc)
-
- some programming code
- blah blah blah
-
- Functions always start with the word function,
then the name, arguments in parentheses, and
curly braces to contain all of the programming
code.
61Introduction to JavaScriptJavaScript Functions
- Function Syntax
- Sometimes you dont give any values for arguments
to a function. - A function with no arguments must still include
the parentheses - function functionName()
-
- some programming code
62Introduction to JavaScriptJavaScript Functions
- Function Syntax
- Each statement line should end with a semi-colon.
While not required, it's good programming
practice. - function functionName()
-
- some programming code
63Introduction to JavaScriptJavaScript Functions
- How to call a function
- You've just seen how to write a function. It
usually goes in the of the web page, or an
external document. - When you want to use a function, we say that we
call the function. - A function just sits there until you call it.
64Introduction to JavaScriptJavaScript Functions
- How to call a function
- You can call a function containing arguments like
this - myfunction(argument1,argument2,etc)
- Call one without arguments like this
- myfunction()
- Just place this call in the code where you need
work done. You need to write the function name
and argument list, that's all.
65Introduction to JavaScriptJavaScript Functions
- How to call a function
- Things to be careful about
- Make sure that you have the same number of
arguments in the function as well as the call to
the function. - JavaScript is case-sensitive, so make sure the
capitalization is the same in the function and
the call to the function. - The function name and the its list of arguments
is called its 'signature'. Make sure the
signatures match!
66Introduction to JavaScriptJavaScript Functions
- Activity 4
- You previously saw a page that used JavaScript to
take a name and then show it, a file called
takeandshow.html. - You will be shown the code that makes up that
file, and be ready to discuss it thoroughly.
After the next lesson you will make your own new
functions!
67Introduction to JavaScript
- JavaScript Operators
- There are many operators in JavaScript for math
and more. Youre already familiar with many of
them. - For example, what do you think JavaScript uses
for adding two numbers together? Right, a
sign! - You will receive a list of operators, but we need
to discuss some of the less familiar ones.
68Introduction to JavaScriptJavaScript Operators
- The basic math operators in JavaScript are
- is "addition"
- is "subtraction"
- is "multiplication"
- / is "division"
69Introduction to JavaScriptJavaScript Operators
- The following example creates two variables and
multiplies them. - var first 4
- var second 5
- var answer first second
- You can probably guess how to use the other
operators!
70Introduction to JavaScriptJavaScript Operators
- Now, many people are confused by this next
operator - "" is NOT the equal sign. JavaScript calls it
the "assignment operator". - If you want to assign a value to something, use
this operator. This assigns whatever is on the
right of the operator into whatever is on the
left of this operator.
71Introduction to JavaScriptJavaScript Operators
- Assignment Operator example
- var first 7
- var second 2
- second first
- What do you think 'second' holds after the code?
If you guessed 7, you're right! The assignment
operator assigns the value of 'first' to it, and
the value of 'first' is 7!
72Introduction to JavaScriptJavaScript Operators
- You might be asking "How do I test if something
equals something else?" - Use the equality operator " " , a double
equal sign. - If you want to see if "a" equals "b", you write
it like this - a b
- You'll see more of this one later.
73Introduction to JavaScriptJavaScript Operators
- Finally, here are the 'increment' and 'decrement'
operators - x means "add one to x"
- x -- means "subtract one from x"
- So, if you had
- var x 5
- x
- x would equal 6 at the end of the code.
74Introduction to JavaScriptJavaScript Operators
- This discussion has certainly not been a complete
coverage of the JavaScript operators, just a
start. - The handout jsOperator.doc lists almost all of
the JavaScript Operators. - It would be good to get familiar with this sheet,
as you will use these operators very often in
JavaScript.
75Introduction to JavaScriptJavaScript Operators
- Activity 5
- Open the "borrowedjs.html" file that you used to
'borrow' some JavaScript from http//javascript.in
ternet.com. - Identify all of the variables and operators used,
and write an explanation of how they are used.
76Introduction to JavaScriptJavaScript Functions
- Putting it all together.
- You will now see a form that represents a basic
calculator. It will take two numbers, perform a
math operation when a button is clicked, and then
display the result in a text field. - The next slides review the basiccalc.html file, a
basic calculator.Note the process and flow of
the HTML and JavaScript code, so you can make
additions and changes to it.
77Introduction to JavaScriptJavaScript Functions
- First, The basic HTML form for the calculator
-
-
First number - size"5" maxlength"5"
-
Second number - size"5" maxlength"5"
-
value"Multiply" onClick"multiply()()" -
Answer - maxlength"15"
78Introduction to JavaScriptJavaScript Functions
- Notice the onClick eventHandler associated with
the button. - value"Multiply" onClick"multiply()"
- onClick calls a function named "multiply()".
This will occur when the button is clicked, since
onClick was put in the button code. - What does "multiply()" do? What does the
function look like, and where is it?
79Introduction to JavaScriptJavaScript Functions
- The multiply() function is in the HEAD of the web
page. - The code for the page is below. See how it takes
two values, multiplies them, and sends them back
to the form's "answer" element. -
- function multiply()
- var a document.numberForm.first.value
- var b document.numberForm.second.value
- document.numberForm.answer.value ab
-
80Introduction to JavaScriptJavaScript Functions
- Activity 6
- You have improved your knowledge of HTML forms
and familiarity with this basiccalc.html
calculator. - Using this example, create your own, more
sophisticated calculator. Make a calculator that
uses the same fields, but has separate buttons
for division and subtraction. For a greater
challenge, create a calculator that does multiple
mathematical calculations with the click of one
button!
81Introduction to JavaScriptJavaScript Functions
- Separating Functions from Pages - Return Values
- In previous examples, like the basiccalc.html,
you have seen a function refer to field on a
form. For example, you saw - function multiply()
- var a document.numberForm.first.value
- This function refers directly to a SPECIFIC field
of a SPECIFIC web page. This type of reference
should be avoided when writing functions, as you
want to make them usable on any page that wants
to.
82Introduction to JavaScriptJavaScript Functions
- Separating Functions from Pages - Return Values
- Instead of referring directly to a web page and
respective fields, make functions as abstract as
possible. The following is a multiply function
example -
- function multiply(a, b)
- return ab
-
83Introduction to JavaScriptJavaScript Functions
- Separating Functions from Pages - Return Values
- Notice that the function has two arguments in the
signature. The HTML sends two arguments, any
arguments, and the function receives them. - function multiply(a, b)
- return ab
-
84Introduction to JavaScriptJavaScript Functions
- Separating Functions from Pages - Return Values
- The function, after receiving the arguments,
manipulates them, and sends back the result via
the return keyword - function multiply(a, b)
- return ab
85Introduction to JavaScriptJavaScript Functions
- Separating Functions from Pages - Return Values
- If the function is designed abstractly enough to
receive any two values from any form, then the
form must be redesigned to send the values to the
function. - The change in the HTML page occurs in the onClick
for the form - onClick"numberForm.answer.valuemultiply(numberFo
rm.first.value, numberForm.second.value
)"
86Introduction to JavaScriptJavaScript Functions
- Separating Functions from Pages - Return Values
- onClick"numberForm.answer.valuemultiply(numberFo
rm.first.value, numberForm.second.value) - Instead of just calling the function, onClick
calls it and sends values in the call (these will
be the "a" and "b" that the function is
expecting). - (Using document is optional, as this refers to
fields in the same page as the onClick.
numberForm.first.value is adequate to send a
value.)
87Introduction to JavaScriptJavaScript Functions
- Separating Functions from Pages - Return Values
- onClick"numberForm.answer.value
multiply(numberForm.first.value,
numberForm.second.value) - Because our new function is returning a value, we
need to assign that value to something. - In this case, we assign our returning value to
the value of the answer field in our form.
88Introduction to JavaScriptJavaScript Functions
- Separating Functions from Pages - Return Values
- function multiply(a, b)
- return ab
-
- Making your functions as abstract as possible is
the key to re-using your code over and over. - For example, the multiply(a, b) function can be
used in an external style sheet for many web
pages.
89Introduction to JavaScriptJavaScript Functions
- Activity 7
- Create a function like the multiply(a, b)
function that takes a certain number of
variables, performs an action on the received
values, and returns a value. - Save this function in an external JavaScript
file, and attach it to a file that calls it, and
passes it two values for manipulation. - Save these files as abstract.js and abstract.html.
90Introduction to JavaScript
- JavaScript Conditional Statements
- Once you have mastered the basic syntax of a
JavaScript function, it is time to move into some
of the more common conditional statement
scripts and syntax. - What are conditional statements? These are
functions that act based on whether or not a
condition is true or false. - There are 3 major conditional statements, and
they will now be covered one at a time.
91Introduction to JavaScriptJavaScript
Conditional Statements
- In JavaScript we have three conditional
statements - if statement - use this statement if you want to
execute a set of code only if a condition is true
- if...else statement - use this statement if you
want to choose one of two sets of lines to
execute - switch statement - use this statement if you want
to select one of many sets of lines to execute
92Introduction to JavaScriptJavaScript
Conditional Statements
- if statement
- This statement is commonly used if the choice is
do this, or do nothing differently. - That is, you are just checking something in a
very simple way. - A common example might be if the name is blank,
tell the user to fill it in.
93Introduction to JavaScriptJavaScript
Conditional Statements
- if statement syntax
- if (condition)
-
- do this if the condition is true
-
- Notice the indented text between curly braces.
This is a very common practice for programmers,
to be able to identify blocks of code quickly.
94Introduction to JavaScriptJavaScript
Conditional Statements
- if statement example - Check for blank name
- The following example will check to see if a
field called "userName" has been filled in, and
pops up a warning box if it isn't filled in. -
- function checkUserName()
- if(document.loginForm.userName.value"")
- alert("Please fill in your name.")
-
95Introduction to JavaScriptJavaScript
Conditional Statements
- if statement example - Check for blank name
- How would this 'checkUserName' function fit in
with a web page? - A while back you made a simple login form, asking
for a user name and password. - Ignoring the password field, the code for the
form would look something like the next slide
96Introduction to JavaScriptJavaScript
Conditional Statements
- if statement example - Check for blank name
-
-
- User Name name"userNameField"
-
- value"Click to login"
onClick"checkUserName()" -
-
-
- Notice the onClick"checkUserName()".
97Introduction to JavaScriptJavaScript
Conditional Statements
- if statement example - Check for blank name
- value"Click to login"
onClick"checkUserName()" -
- onClick is another 'eventHandler'. You can put
this on any button. When you click on the
button, the onClick will call its function. - In this case, onClick calls the function
checkUserName(), which is located in the head of
the document (next slide)
98Introduction to JavaScriptJavaScript
Conditional Statements
- if statement example - Check for blank name
- Login Form
-
- function checkUserName()
- if(document.loginForm.userNameField.value
"") - alert("Please fill in your name.")
-
-
-
- This says "if the name field is blank, pop up a
window saying 'Please fill in your name.'"
99Introduction to JavaScriptJavaScript
Conditional Statements
- if statement example - alert window
- Just a side note the 'alert' window is another
ready-made JavaScript function. The syntax is
simple - Write the word 'alert', put whatever words you
want on the box inside parentheses and quotes.
For example, a box that says "Hi there" would be - alert("Hi
there")
100Introduction to JavaScriptJavaScript
Conditional Statements
- if statement example - short activity
- Try adding the previous pieces of code together
in one file. Call this file "nameCheck.html". - Make sure you test that a window pops up IF the
name field is blank, but it doesn't pop up if the
name field has something in it.
101Introduction to JavaScriptJavaScript
Conditional Statements
- if...else statement
- The 'if' statement performs one action if
something was true. - If we want one action taken if the condition is
true, and a different action if the condition is
false, we can use the if...else statement. - For example, if the name field is blank tell them
to enter a name, or else say Welcome!!! if it's
not blank.
102Introduction to JavaScriptJavaScript
Conditional Statements
- if...else statement syntax
- if (condition)
- code to be executed if condition is true
- else
- code to be executed if condition is false
-
- This is just like the 'if' code, except we added
another chunk!
103Introduction to JavaScriptJavaScript
Conditional Statements
- if...else statement example
- This is the original 'if' from the nameCheck.html
file. It says 'if the name is blank'. - function checkUserName()
- if(document.loginForm.userNameField.value
"") - alert("Please fill in your name.")
-
-
- All we will do is add an 'else' condition.
104Introduction to JavaScriptJavaScript
Conditional Statements
- if...else statement example
- function checkUserName()
- if(document.loginForm.userNameField.value
"") - alert("Please fill in your name.")
- else
- alert("Welcome!!!")
-
-
- Now we options for both blank and non-blank
names!
105Introduction to JavaScriptJavaScript
Conditional Statements
- if...else statement syntax notes
- function checkUserName()
- if(document.loginForm.userNameField.value
"") - alert("Please fill in your name.")
- else
- alert("Welcome!!!")
-
-
- Note that there are 3 sets of curly braces one
for the function, one for the 'if' condition, and
one for the 'else' condition. This helps to
group statements together.
106Introduction to JavaScriptJavaScript
Conditional Statements
- if...else statement syntax notes
- function checkUserName()
- if(document.loginForm.userNameField.value
"") - alert("Please fill in your name.")
- else
- alert("Welcome!!!")
-
-
- Also notice that one 'alert' line has a
semi-colon at the end of the line, while the
other doesn't. While this is optional, it is
highly recommended that you use them after each
statement.
107Introduction to JavaScriptJavaScript
Conditional Statements
- Activity 8
- if...else statement activity
- Try editing your script in your 'namecheck.html'
file to use an 'else' clause. - Instead of
- alert("Welcome!!!")
- try the following line and explain what it does
- alert("Welcome " document.loginForm.userNa
meField.value "!!") - Save this file as 'namecheck2.html'.
108Introduction to JavaScriptJavaScript
Conditional Statements
- The last conditional statement to cover is the
switch statement. - Use this statement if you want to select one of
many sets of lines to execute. - For example, if you offer the visitor a choice of
item A, B, C, or D, that doesnt work well with
if, else, but it does with a 'switch'. - Keep this statement in mind if you have a list
where the user chooses only one. The following
slide is an example of a basic switch statement
109Introduction to JavaScriptJavaScript
Conditional Statements
- Switch statement syntax (for two items)
- switch (expression)
- case label1
- code to be executed if expression label1
- break
- case label2
- code to be executed if expression label2
- break
- default
- code to be executed if expression is different
from both label1 and label2
110Introduction to JavaScriptJavaScript
Conditional Statements
- Switch statement syntax (for two items)
- switch (expression)
-
-
- Begin with the word switch.
- Give it a value or expression to evaluate, like a
variable. - Be sure to surround all of the switch statement
with curly braces.
111Introduction to JavaScriptJavaScript
Conditional Statements
- Switch statement syntax (for two items)
- switch (expression)
- case label1
- .
-
- The next line begins with the word case. Case is
a keyword, and it lists one case to compare to
the expression. - In this scenario, we are looking to see if label1
is equal to expression.
112Introduction to JavaScriptJavaScript
Conditional Statements
- Switch statement syntax (for two items)
- case label1
- code to be executed if expression label1
- break
- If label1 does equal expression, then the code
for case label1 is executed. - After the code is executed, the break keyword
jumps to the end of the switch, skipping the
other cases.
113Introduction to JavaScriptJavaScript
Conditional Statements
- Switch statement syntax (for two items)
- case label2
- code to be executed if expression label2
- break
- If label1 does NOT equal expression, then case
label2 is evaluated to see if label2 equals
expression. - If label2 equals expression, code in the label2
area is executed. - After the code is executed, the break keyword
jumps to the end of the switch, skipping the
other cases.
114Introduction to JavaScriptJavaScript
Conditional Statements
- Switch statement syntax (for two items)
- The switch statement runs through every case
until it finds a match between the expression and
the label. - It will read all of the cases if the break
keyword is not used, so make sure to use it in
every case. - Finally, there is a default as the last case, in
the situation that no label matched the
expression.
115Introduction to JavaScriptJavaScript
Conditional Statements
- Switch statement syntax (for two items)
- You can create a switch statement for as many
cases as you'd like. - The following slide has an HTML form that asks
whether you should get an A or a B in the class. - The slide following the HTML is the JavaScript
switch statement that evaluates and responds to
your input.
116Introduction to JavaScriptJavaScript
Conditional Statements
- Switch statement syntax (Grade Choice HTML
example) -
- Enter the grade that you deserve for this
class
- Please use capital letters, and use only A or
B. -
- maxlength"1"
- value"Submit Grade" onClick"checkGrade()"
-
-
117Introduction to JavaScriptJavaScript
Conditional Statements
- Switch statement syntax (Grade Choice JavaScript
example) - function checkGrade()
- var yourGrade document.gradeForm.grade.value
- switch(yourGrade)
- case "A"
- alert("You certainly deserve it.")
- break
- case "B"
- alert("You deserve more.")
- break
- default
- alert("You did not follow instructions.")
-
118Introduction to JavaScriptJavaScript
Conditional Statements
- Activity 9
- Your first activity is to take the JavaScript
function and HTML form code supplied, and create
one file called checkGrade.html. - Since the code supplied only responds to A or B
grades, create unique responses to other grades
entered by the user. - For an advanced challenge, try to allow the users
to enter capitals or small letters! (You'll need
some extra online help for that.)
119Introduction to JavaScript
- JavaScript Looping Statements
- Looping? Whats that, and what does it have to
do with this? - "Loops" are very popular methods in programming
that allow you to perform the same operation over
and over again, for a specified number of times. - There are three main loops to introduce for,
while, and do while.
120Introduction to JavaScriptJavaScript Looping
Statements
- In JavaScript we have the following looping
statements - while - loops through a block of code AS LONG AS
A CONDITION IS TRUE -
- do...while - loops through a block of code AT
LEAST ONCE, and then repeats the loop as long as
a condition is true - for - run statements a SPECIFIED NUMBER of times
121Introduction to JavaScriptJavaScript Looping
Statements
- "while" loop - loops through a block of code as
long as a condition is true - Heres an example of when to use the "while"
loop - Imagine you have a list of numbers that you want
to print, but you dont know how many there are.
- You think While there are still numbers in the
list, print the next number.
122Introduction to JavaScriptJavaScript Looping
Statements
- "while" loop syntax
- while (condition)
-
- code to be executed
-
- This block begins with the word while, has a
test in parentheses, and has curly braces holding
the statements to perform actions. - The next slide has an example.
123Introduction to JavaScriptJavaScript Looping
Statements
- "while" loop example
-
- var maximum 10
- var counter 0
- while (counter
-
- document.write("The count is " counter)
- document.write("
") - counter
-
124Introduction to JavaScriptJavaScript Looping
Statements
- "while" loop
- var maximum 10
- var counter 0
- .
- The first two lines in the code are variables.
Maximum is what the counter might reach in the
loop, counter is just that, a counter for the
loop. - As a developer, you might only get the variable
maximum, and not know it's value. (Pretend it's
not there, but use it!)
125Introduction to JavaScriptJavaScript Looping
Statements
- "while" loop
-
- while (counter
-
- This code can be read as "while the counter
variable is less than or equal to the maximum
variable, do the next steps".
126Introduction to JavaScriptJavaScript Looping
Statements
- "while" loop
-
- document.write("The count is " counter)
- document.write("
") -
- These next two lines write on the page. It will
write "The count is " followed by the value of
counter, then a line break.
127Introduction to JavaScriptJavaScript Looping
Statements
- "while" loop
-
- counter
-
- Finally, the counter variable is incremented and
the statements in the while loop end. - This sends the loop back up to the while test to
see if counter is still less than or equal to
maximum. If it is, then repeat the statements.
If not, go to the first line of code after the
while loop.
128Introduction to JavaScriptJavaScript Looping
Statements
- "while" loop activity
- Take the 'while' loop code discussed in the
previous slides, and put it into the body of a
web page. - Try changing the values of counter and maximum to
see the various results you might get. - Save your file as whilelooper.html.
129Introduction to JavaScriptJavaScript Looping
Statements
- do...while
- A "dowhile" loop is very similar to a "while"
loop. - The only difference is that the "dowhile" loops
through a block of code AT LEAST ONCE before
testing a condition, and then repeats the loop as
long as a condition is true - When reading the code, this will look like the
while loop, but upside-down.
130Introduction to JavaScriptJavaScript Looping
Statements
- dowhile syntax
- do
-
- code to be executed
- while (condition)
- Begin with the word do, use curly braces to
contain the statements, and end with a while
condition to test the value.
131Introduction to JavaScriptJavaScript Looping
Statements
- dowhile example - What will this example write?
-
- i 0
- do
-
- document.write("The number is " i)
- document.write("
") - i
-
- while (i
-
- Try it in a page!
132Introduction to JavaScriptJavaScript Looping
Statements
- "for" loop
- If you would like to dictate the exact number of
loops, then the for loop is for you! - The for loop and while loop are among the
most frequently used statements in programming,
as they can help you to do numerous jobs in a
very short time.
133Introduction to JavaScriptJavaScript Looping
Statements
- "for" syntax
- for (initialization condition increment)
-
- code to be executed
-
- Start this loop off with the keyword for, and
surround the code statements with curly braces.
134Introduction to JavaScriptJavaScript Looping
Statements
- "for" syntax
- for (initialization condition increment)
-
- code to be executed
-
- initialization this is the initial value,
usually a counter. The previous loops used i0
to start with a value, and that same expression
could be used here.
135Introduction to JavaScriptJavaScript Looping
Statements
- "for" syntax
- for (initialization condition increment)
-
- code to be executed
-
- condition this is very similar to what the
while loop uses to test. - We could used ivariable each loop.
136Introduction to JavaScriptJavaScript Looping
Statements
- "for" syntax
- for (initialization condition increment)
-
- code to be executed
-
- increment increment means to add a value.
- In the while examples, you saw counter as the
incrementer, which adds 1 to the value of
counter. You can add more than one each time if
you'd like!
137Introduction to JavaScriptJavaScript Looping
Statements
- "for" syntax
- for (initialization condition increment)
-
- code to be executed
-
- Lastly, be sure to separate the 3 arguments in
the for loop with semi-colons. These are
necessary for your code to work.
138Introduction to JavaScriptJavaScript Looping
Statements
- "for" loop example
-
- for (i 0 i
-
- document.write("The number is " i)
- document.write("
") -
-
- This example will perform a for loop. Try it out!
139Introduction to JavaScriptJavaScript Looping
Statements
- Activity 10
- At this point, make a page with all 3 types of
loops demonstrated. - Your page should teach the reader the differences
between the 3 loops, and demonstrate the results. - Call this page "triplelooper.html".
140Introduction to JavaScript
- JavaScript Objects
- This is the last lesson on JavaScript.
- Besides all of the HTML forms and the JavaScript
statements, there are some built-in objects that
can do other, special things with information.
These special objects are called Objects. - These objects will be covered briefly, with an
example and a source for further instruction.
141Introduction to JavaScriptJavaScript Objects
- Objects
- The main objects to be covered here are
- String
- Array
- Math
- Window
- Date
- Browser
142Introduction to JavaScriptJavaScript Objects
- String Object
- A 'string' is a set of characters, like a word or
sentence. The String object is used to work with
text. It has certain built-in properties and
methods. - One popular method is 'indexOf()'. This can tell
the starting location of a letter or word inside
of a string. For example, to test if the _at_
symbol is in an email address, use - var pos email.indexOf("_at_"). This returns the
position of the _at_.
143Introduction to JavaScriptJavaScript Objects
- Math Object
- The Math object performs some of the more
complicated math work that the normal operators
cannot do. - For example, it can do 7 to the 3rd power
- var answer Math.pow(7,3)
- Or it can do trigonometry, finding the cosine of
45 - var answer Math.cos(45).
144Introduction to JavaScriptJavaScript Objects
- Browser Object
- It's strange, but the Browser object uses the
name navigator. - If you would like to tell what kind of browser
the visitor is using, it's possible with this
object! - Try this in your code
- document.write("You are browsing this site with
" navigator.appName)
145Introduction to JavaScriptJavaScript Objects
- Date Object
- The Date object can deliver a lot of information
regarding the day, date, time, etc. - First, create a variable that holds the date like
this - var today new Date()
- Then, do things like print out the date
- document.write(today)
146Introduction to JavaScriptJavaScript Objects
- JavaScript Object Information
- For more examples of JavaScript Objects and their
properties and methods, go to - http//www.w3schools.com/js/default.asp and look
under References. - or
- h