Functions and Event Handlers

Download Report

Transcript Functions and Event Handlers

Functions and Event Handlers
CST 200 - JavaScript
Objectives
• Introduce JavaScript functions
• Understand how to pass information to
JavaScript functions
• Create user-defined functions
• Identify event handlers
• Use event handlers to call JavaScript functions
2
Functions
• A function is a block of code that performs
some action when someone calls it
– A function can take some input and return a result
5
x
f(x) = x2
25
When the value 5 is
passed into the function,
the value 25 is returned
3
Functions – Parameters/Arguments
• The information passed into a function is
called parameters or arguments
6
y
f(y) = y + 10
16
The function parameter is the variable
we declare in the function declaration.
This function has one parameter named y
The function argument is the value passed
into the function in place of the parameter.
Above, 6 is the argument passed as parameter y
4
Functions – Parameters/Arguments (2)
• Each time we call a function we can pass in different
arguments
This function has one
parameter named Z
52
z
24
z
f(z) = z - 12
40
When we pass 52
as an argument,
the value 40 is returned
f(z) = z - 12
What value is returned when we pass 24 as an argument ?
5
Functions – Multiple Parameters
• A function can have more than one parameter
12
a
24
sum( a , b ) = a + b
36
b
This function has two
parameters named a and b
When a = 12 and b = 24
the function returns 36
100
a
25
b
sum( a , b ) = a + b
What is returned?
6
Functions – Zero Parameters
• A function can have zero parameters
random( ) = [ random # between 1 and 10]
[ 1 .. 10 ]
This random( ) function has zero
parameters and randomly returns
a number between 1 and 10
7
Functions – Side Effects
• Some functions do not return a value
– Instead, the function performs some observable
action with the outside world, called a side effect
– Functions that print messages, display pop-ups,
send email, etc. are examples of functions with
side effects
8
Functions – Side Effects (cont)
• The window.alert( ) function is an example of
a function with a side effect
"hello world"
txt
window.alert( )
The alert( ) function takes a
string value as a parameter,
outputs the string value in a
popup box, and then returns
nothing
9
Functions – Side Effects (cont)
• The side effects of a function are extremely
consequential and important
• Understanding the side effects of a function is
important
• Most of the JavaScript functions we use and
design will have side effects
– The functions will perform observable actions that
output information to the web page or modify
web page elements
10
Functions - Programming
• In programming languages, a function is a
named piece of code, that can be called from
within a program
• Some functions are built-in to the
programming language
– Built-in
• Some functions are defined by the
programmer
– User-defined
11
Built-in JavaScript Functions
• We have already seen examples of built-in
JavaScript functions:
window.alert( )
window.prompt( )
document.write( )
parseInt( )
12
Built-in JavaScript Function
• The window.prompt( ) function is a built-in JavaScript
function
Example function call:
"Enter Name"
txt
window.prompt("Enter Name:");
window.prompt( )
"William"
The prompt( ) function takes
a string value as a parameter,
outputs the string value in a
dialog box, and then returns
the string entered by the user
13
Built-In JavaScript Functions
• The parseInt( ) function is a built-in JavaScript
function
Example function call:
parseInt( 85.275 );
parseInt( )
85.275
val
Does the parseInt( )
function have any side
effects ?
What is returned?
14
User-Defined Functions
• We can define our own functions to perform
some set of actions
• We declare functions through a function
declaration
– Function declarations should be placed within the
HEAD element of a html document
– This ensures the function will be loaded into
memory, and available to be called from anywhere
within the html document
15
JavaScript Function Syntax
• A function is written as a code block (inside curly
{ } braces), preceded by the function keyword
• In the function declaration, we specify any and all
parameters the function will take in
Function Syntax:
function functionName( par1, par2, … ,parN )
{
some code to be executed
}
16
Example #1: sum() function
• Revisiting our earlier
example, below is a
simple sum() function
a
sum( a , b ) = a + b
b
function sum( a , b ) {
return a + b;
}
17
Example #2: avg() function
a
avg( a , b ) = (a + b ) / 2
b
function avg( a , b ) {
return ( a + b ) / 2;
}
18
Placement of user-defined functions
• User defined functions should be declared in a scriplet
(SCRIPT element) in the HEAD section of the web page
<html>
<head>
<script type = "text/javascript">
function sum( a , b ) {
return a + b;
}
function avg( a , b ) {
return ( a + b ) / 2;
}
</script>
</head>
…
<body>
…
<script type = "text/javascript">
var x = sum( 15 , 12 );
var t = avg( 105 , 65 );
</script>
…
</body>
</html>
define functions
call functions
19
Placement of user-defined functions (2)
• Many times user-defined functions will be defined in an
external JavaScript file
function sum( a , b ) {
return a + b;
}
function avg( a , b ) {
return ( a + b ) / 2;
}
functions.js
page.html
<html>
<head>
<script type = "text/javascript"
src = "functions.js" >
</script>
</head>
…
<body>
page.html
…
<script type = "text/javascript">
var x = 10;
var y = 25;
var z = sum( x , y );
</script>
…
</body>
</html>
20
Functions – Control Flow
• When a function is called, the control flow jumps to the
function code
<body>
<script type = "text/javascript">
…
…
1
…
2
…
var z = functionA( x , y );
…
…
4
…
5
…
…
</script>
function functionA( a , b ) {
…
…
3
…
…
return val;
}
</body>
21
Functions – Local Variables
• Some functions declare variables within the function, called
local variables
• These variables only exist within the function and cannot be
used outside the function
Local variable
function calcShipping( state ) {
var shippingCost;
<body>
if ( state == "CT" )
shippingCost = 8.25;
else if (state == "MA" )
shippingCost = 12.60;
else
shippingCost = 18.20;
<script type = "text/javascript">
…
var state = prompt("Enter State:");
var cost = calcShipping( state );
…
</script>
return shippingCost;
}
</body>
22
Functions – Local Variables (cont)
• If we tried to access a local variable outside the function, we
would get an error
function calcShipping( state ) {
var shippingCost;
if ( state == "CT" )
shippingCost = 8.25;
else if (state == "MA" )
shippingCost = 12.60;
else
shippingCost = 18.20;
return shippingCost;
}
<body>
<script type = "text/javascript">
…
var state = prompt("Enter State:");
var cost = calcShipping( state );
…
document.write( shippingCost );
</script>
</body>
Error: the variable shippingCost
only exists within the calcShipping( )
function
23
Calling Functions – Event Handlers
• Functions can be called from anywhere in a
JavaScript scriptlet, or by an event handler
• Event handlers are JavaScript code that
execute when the user performs some action,
or triggers an event
• Event handlers can be placed within the
opening tag of most html elements
24
JavaScript Events
• Examples of HTML events:
– When a user clicks the mouse
– When a web page has loaded
– When an image has been loaded
– When the mouse moves over an element
– When an input field is changed
– When an HTML form is submitted
– When a user strokes a key
25
onclick/onmouseover Events
• The onclick event is triggered when the user clicks
the mouse on a specified HTML element
• The onmouseover event is triggered when the user
mouses over a specified HTML element.
<html>
<body>
<h1>Test Events Page</h1>
<h2 onclick="alert('you clicked me')" >
Click on me!</h2>
<h2 onmouseover="alert('you hovered over me')" >
Hover over me!</h2>
</body>
</html>
26
onclick Event – change Background
<html>
<head>
<script>
function changeBGcolor() {
document.bgColor = prompt("Enter background color:");
}
</script>
</head>
<body>
<h1>Background Color Page</h1>
<button onclick="changeBGcolor()">Change color</button>
</body>
</html>
27
Summary
• JavaScript language contains built-in and userdefined functions
• A function is a block of code that performs some
action when it is called
• Information passed to functions are called
parameters or arguments
• Functions can be called from anywhere within a
scriplet, or by an event handler
• Event handlers are JavaScript code that executes
when the user performs some action, or triggers
an event
28