ch6 - Java Part2 Events Functions

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 39

Assist. Prof. Dr.

Fatih ABUT
2

2
3

Why also use client-side scripting?


} client-side scripting (e.g. JavaScript) benefits:
◦ usability: can modify a page without having to post
back to the server (faster UI)
◦ efficiency: can make small, quick changes to page
without waiting for server
◦ event-driven: can respond to user actions like clicks
and key presses

3
4

} server-side programming (e.g. PHP) benefits:


◦ security: has access to server's private data; client
can't see source code
◦ compatibility: not subject to browser compatibility
issues
◦ power: can write files, open connections to servers,
connect to databases, ...

4
} Functions are a collection of JavaScript
statement that performs a specified task
} Functions are used whenever it is necessary
to repeat an operation
} Statements placed into functions can be
evaluated in response to user events

5
} Functions have inputs and outputs
} The inputs are passed into the function and
are known as arguments or parameters
} Think of a function as a “black box” which
performs an operation

6
} The most common way to define a function is
with the function statement.
} The function statement consists of the
function keyword followed by the name of the
function, a comma-separated list of
parameter names in parentheses, and the
statements which contain the body of the
function enclosed in curly braces
function name() {
statement ;
statement ;
...
statement ;
} JS
7
function square(x) Name of Function:
{return x*x;} square

z = 3; Input/Argument: x
sqr_z = square(z);
Output: x*x

8
function sum_of_squares(num1,num2)
{return (num1*num1) + (num2*num2);}

function sum_of_squares(num1,num2)
{return (square(num1) + square(num2));}

9
} Events are actions that can be detected by JavaScript

} Every element on a web page has certain events which can


trigger JavaScript functions

} Often placed within the HTML tag


◦ <tag attribute1 attribute2 onEventName="javascript code;">
◦ <a href="" onMouseOver="popupFunc();">

} The set of all events which may occur and the page elements
on which they can occur is part of the Document Object Model
(DOM) not JavaScript
◦ Browsers don’t necessarily share the same set of events

10
1
0
Event Occurs when... Event Handler
} click User clicks on form element or link onClick
} change User changes value of text, textarea, or select element onChange
} focus User gives form element input focus onFocus
} blur User removes input focus from form element onBlur
} mouseover User moves mouse pointer over a link or anchor onMouseOver
} mouseout User moves mouse pointer off of link or anchor onMouseOut
} select User selects form element's input field onSelect
} submit User submits a form onSubmit
} resize User resizes the browser window onResize
} load User loads the page in the Navigator onLoad
} unload User exits the page onUnload

11
12

¨ split breaks apart a string into an array


using a delimiter
¤ can also be used with regular expressions
(seen later)
¨ join merges an array into a single string,
placing a delimiter between them
12
13

¨ you are used to programs start with a


main method
¨ JavaScript programs instead wait for user
actions called events and respond to them
¨ event-driven programming: writing
programs driven by user events
¨ Let's write a page with a clickable button
that pops up a "Hello, World" window...

13
14

<button>Click me!</button> HTML

} button's text appears inside tag; can also


contain images
} To make a responsive button or other UI
control:
1. choose the control (e.g. button) and event (e.g.
mouse 1. click) of interest
2. write a JavaScript function to run when the event
occurs
3. attach the function to the event on the control

14
<element attributes onclick="function();">...
HTML

<button onclick="myFunction();">Click me!</button>


HTML

} JavaScript functions can be set as event handlers


◦ when you interact with the element, the function will
execute
} onclick is just one of many event HTML attributes
we'll use
} but popping up an alert window is disruptive and
annoying
◦ A better user experience would be to have the message
appear on the page...
15
16

} The HTML DOM is a


standard object model and programming
interface for HTML

} It defines:
◦ The HTML elements as objects
◦ The properties of all HTML elements
◦ The methods to access all HTML
elements
◦ The events for all HTML elements

} In other words: The HTML DOM is a


standard for how to get, change, add, or
delete HTML elements.

16
17

17
18

var name = document.getElementById("id");


JS

<button onclick="changeText();">Click me!</button>


<span id="output">replace me</span>
<input id="textbox" type="text" /> HTML

function changeText() {
var span = document.getElementById("output");
var textBox = document.getElementById("textbox");

textbox.style.color = "red";
span.innerHTML = textBox.value;

} JS

18
19

¨ document.getElementById returns the


DOM object for an element with a given id
¨ can change the text inside most elements
by setting the innerHTML property
¨ can change the text in form controls by
setting the value property

19
20

20
21

function changeText() {
//grab or initialize text here

// font styles added by JS:


text.style.fontSize = "13pt";
text.style.fontFamily = "Comic Sans MS";
text.style.color = "red"; // or pink?
} JS

21
22

var ahmet = null;


var mehmet = 9;
// at this point in the code,
// ahmet is null
// Mehmet is 9
// ayse is undefined
JS

¨ undefined : has not been declared, does not exist


¨ null : exists, but was specifically assigned an
empty or null value
¨ Why does JavaScript have both of these?

22
23
if (condition) {
statements;
} else if (condition) {
statements;
} else {
statements;
}
JS

¨ identical structure to Java's if/else


statement
¨ JavaScript allows almost anything as a
condition

23
24

switch(expression) {
case x:
code block
break;
case y:
code block
break;
default:
code block
} JS

} The switch expression is evaluated once.


} The value of the expression is compared with the
values of each case.
} If there is a match, the associated block of code is
executed. 24
25

var sum = 0;
for (var i = 0; i < 100; i++) {
sum = sum + i;
} JS

var s1 = "hello";
var s2 = "";
for (var i = 0; i < s1.length; i++) {
s2 += s1.charAt(i) + s1.charAt(i);
}
// What is stored in s2 ? JS

25
26

while (condition) {
statements;
} JS

do {
statements;
} while (condition);
JS

26
} JavaScript defines two instruction statements that cause
immediate, non-sequential alteration of normal
sequential instruction processing

} Break Logic
◦ Execution of a break ; statement at any location in a
loop-structure causes immediate exit from the loop-
structure

} Continue Logic
◦ Execution of a continue ; statement at any location in
a loop-structure causes execution to continue at the
beginning of the loop structure (at the next loop
iteration) while skipping the remaining statements.
27
} Break Logic
◦ Execution of a break ; statement at any location in a loop-
structure causes immediate exit from the loop-structure

for ( var k = 0 ; k < 10 ; k++ ) {


if ( k == 5 ) break ;
document.write(k)
}

} Produces output : 0, 1, 2, 3, 4

28
} Continue Logic
◦ Execution of a continue ; statement at any location in
a loop-structure causes execution to continue at the
beginning of the loop structure (at the next loop
iteration) while skipping the remaining statements.

for ( k = 0 ; k < 5 ; k++ ) {


if ( k == 3 ) continue ;
document.write(k);
}
} Produces output : 0, 1, 2, 4

29
30

alert("message"); // message
confirm("message"); // returns true or false
prompt("message"); // returns user input string
JS

30
l Global object
– Always available
– Provides 7 methods
– Do not need to explicitly reference Global before
method call
– Also holds all global variables, user defined
functions

31
Global function Description
escape This function takes a string argument and returns a
string in which all spaces, punctuation, accent
characters and any other character that is not in the
ASCII character set (see Appendix D, ASCII
Character Set) are encoded in a hexadecimal format
(see Appendix E, Number Systems) that can be
represented on all platforms.
eval This function takes a string argument representing
JavaScript code to execute. The JavaScript
interpreter evaluates the code and executes it when
the eval function is called. This function allows
JavaScript code to be stored as strings and executed
dynamically.
isFinite This function takes a numeric argument and returns
true if the value of the argument is not NaN,
Number.POSITIVE_INFINITY or
Number.NEGATIVE_INFINITY; otherwise, the
function returns false.
isNaN This function takes a numeric argument and returns
true if the value of the argument is not a number;
otherwise, it returns false. The function is
commonly used with the return value of parseInt
or parseFloat to determine whether the result is a
proper numeric value.
Fig. 10.9 JavaScript global functions.

32
Global function Description
parseFloat This function takes a string argument and attempts
to convert the beginning of the string into a floating-
point value. If the conversion is unsuccessful, the
function returns NaN; otherwise, it returns the
converted value (e.g., parseFloat( "abc123.45" )
returns NaN, and parseFloat( "123.45abc" )
returns the value 123.45).
parseInt This function takes a string argument and attempts
to convert the beginning of the string into an integer
value. If the conversion is unsuccessful, the function
returns NaN; otherwise, it returns the converted
value (e.g., parseInt( "abc123" ) returns NaN, and
parseInt( "123abc" ) returns the integer value
123). This function takes an optional second
argument, from 2 to 36, specifying the radix (or
base) of the number. Base 2 indicates that the first
argument string is in binary format, base 8 indicates
that the first argument string is in octal format and
base 16 indicates that the first argument string is in
hexadecimal format. See see Appendex E, Number
Systems, for more information on binary, octal and
hexadecimal numbers.
unescape This function takes a string as its argument and
returns a string in which all characters previously
encoded with escape are decoded.
Fig. 10.9 JavaScript global functions.

33
} Exception handling in JavaScript is almost the same
as in Java
} throw expression creates and throws an exception
◦ The expression is the value of the exception, and can be of
any type (often, it's a literal String)
} try {
statements to try
} catch (e) { // Notice: no type declaration for e
exception handling statements
} finally { // optional, as usual
code that is always executed
}
◦ With this form, there is only one catch clause

34
3
4
} try {
statements to try
} catch (e if test1) {
exception handling for the case that test1 is true
} catch (e if test2) {
exception handling for when test1 is false and test2
is true
} catch (e) {
exception handling for when both test1 and test2 are
false
} finally { // optional, as usual
code that is always executed
}
} Typically, the test would be something like
e == "InvalidNameException"

35
3
5
} Six error types are implemented in JavaScript:
◦ EvalError - Raised by eval when it’s used incorrectly
◦ RangeError - Raised when the numeric value exceeds its range
◦ ReferenceError - Raised when an invalid reference is used
◦ SyntaxError - Raised when there is invalid syntax used
◦ TypeError - Raised when a variable is not if the type expected
◦ URIError - Raised when encodeURI() or decodeURI() is used incorrectly
◦ There is an operator called ‘instanceof’ that can be very useful in exception
handling. It can tell you whether a certain error is one of the known types
listed above.

36
37

var arr = null;


try {
console.log( arr[4] ); //will generate a TypeError exception
}
catch (e if e instanceof TypeError) {
// statements to handle TypeError exceptions
} catch (e if e instanceof RangeError) {
// statements to handle RangeError exceptions
} catch (e if e instanceof EvalError) {
// statements to handle EvalError exceptions
document.write("type error");
} catch (e) {
// statements to handle any unspecified exceptions
}

37
38<p>Please input a number between 5 and 10:</p>
<input type="text“ id="demo" >
<button type="button" onclick="myFunction()">Test Input</button>
<p id="p01"></p>

<script>
function myFunction() {
var message, x;
message = document.getElementById("p01");
message.innerHTML = "";
x = document.getElementById("demo").value;
try {
if(x == "") throw "empty";
if(isNaN(x)) throw "not a number";
x = Number(x);
if(x < 5) throw "too low";
if(x > 10) throw "too high";
}
catch(err) {
message.innerHTML = "Input is " + err;
}
}
</script> 38
39

<script src="filename" type="text/javascript"></script>


HTML

} script tag should be placed in HTML page's


head
} script code is stored in a separate .js file
} JS code can be placed directly in the HTML
file's body or head (like CSS)
◦ but this is bad style (should separate content,
presentation, and behavior

39

You might also like