pemrograman teknologi internet w06: functions and events

31
Pemrograman Pemrograman Teknologi Teknologi Internet Internet W06: W06: Functions and Events Functions and Events

Upload: winifred-parker

Post on 01-Jan-2016

221 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Pemrograman Teknologi Internet W06: Functions and Events

Pemrograman Pemrograman Teknologi Teknologi InternetInternet

W06:W06:

Functions and EventsFunctions and Events

Page 2: Pemrograman Teknologi Internet W06: Functions and Events

2

ObjectivesObjectives

FunctionsFunctions User-defined FunctionsUser-defined Functions

Event HandlingEvent Handling

Page 3: Pemrograman Teknologi Internet W06: Functions and Events

3

Function IntroductionFunction Introduction

Experience has shown that the best way Experience has shown that the best way to develop and maintain a large to develop and maintain a large program is to construct it from small, program is to construct it from small, simple pieces, or modules.simple pieces, or modules. This technique is called divide and conquer.This technique is called divide and conquer.

JavaScript facilitates the design, implementation, operation and maintenance of large scripts by using “functions”.

Page 4: Pemrograman Teknologi Internet W06: Functions and Events

4

Function IntroductionFunction Introductionfunction function-name( parameter-list ){

declarations and statements}

ModulesModules in JavaScript are called in JavaScript are called functionsfunctions. . JavaScript programs are written by JavaScript programs are written by

combining new functions that the combining new functions that the programmer writes with “prepackaged” programmer writes with “prepackaged” functions and objects available in JavaScript. functions and objects available in JavaScript. The prepackaged functions that belong to The prepackaged functions that belong to

JavaScript objects (such as Math.pow and JavaScript objects (such as Math.pow and Math.round, introduced previously) are often Math.round, introduced previously) are often called methodscalled methods

Page 5: Pemrograman Teknologi Internet W06: Functions and Events

5

Worker-Function Worker-Function RelationshipRelationship

A function is invoked (i.e., made to perform its designated task) by a function call. The function call specifies the function name and provides information (as arguments) that the called function needs to perform its task.

Page 6: Pemrograman Teknologi Internet W06: Functions and Events

6

Function DefinitionFunction Definition Consider: function square to calculate the

squares of the integers from 1 to 10:

for ( var x = 1; x <= 10; ++x ) {document.writeln( "The square of " + x + " is " +

square( x ) + "<br />" );}

// The following square function's body is executed// only when the function is explicitly called.

// square function definitionfunction square( y ){

return y * y;}

Page 7: Pemrograman Teknologi Internet W06: Functions and Events

7

Function DefinitionFunction Definitionfunction square( y ){

return y * y;}

The definition of function square shows that square The definition of function square shows that square expects a single parameter y. expects a single parameter y.

Function square uses this name in its body to Function square uses this name in its body to manipulate the value passed to square from line 20. manipulate the value passed to square from line 20.

The return statement in square passes the result of The return statement in square passes the result of the calculation y * y back to the calling function. the calculation y * y back to the calling function.

Note:Note: JavaScript keyword var is not used to declare JavaScript keyword var is not used to declare variables in the parameter list of a function.variables in the parameter list of a function.

Page 8: Pemrograman Teknologi Internet W06: Functions and Events

8

Return ValuesReturn Values There are three ways to return control to the

point at which a function was invoked. If the function does not return a result, control

returns when the program reaches the function ending right brace

or by executing the statement return; If the function does return a result, the

statement return expression;

// maximum method definition (called from line 25)function maximum( x, y, z ){return Math.max( x, Math.max( y, z ) );}

Page 9: Pemrograman Teknologi Internet W06: Functions and Events

9

Math.random()Math.random() General Use:General Use:

var randomValue = Math.random();var randomValue = Math.random();

Method random generates a floating-point value Method random generates a floating-point value from 0.0 up to, but not including, 1.0. from 0.0 up to, but not including, 1.0.

If random truly produces values at random, then If random truly produces values at random, then every value from 0.0 up to, but not including, 1.0 every value from 0.0 up to, but not including, 1.0 has an equal chance (or probability) of being has an equal chance (or probability) of being chosen each time random is calledchosen each time random is called

Example:Example:

var x = Math.floor( 1 + Math.random() * 6 );

Page 10: Pemrograman Teknologi Internet W06: Functions and Events

10

Global vs Method (Object Global vs Method (Object Functions)Functions)

The Global object contains all the global variables in the script, all the user-defined functions in the script. Example: parseInt, parseFloat

Because global functions and user-defined functions are part of the Global object, some JavaScript programmers refer to these functions as methods. the term method only when referring to a function that is

called for a particular object (such as Math.random()). You do not need to use the Global object directly;

JavaScript uses it for you.

Page 11: Pemrograman Teknologi Internet W06: Functions and Events

11

How to wrap up as a How to wrap up as a function?function?

function Random(startLimit, endLimit) {function Random(startLimit, endLimit) {

return Math.floor( startLimit + Math.random() * return Math.floor( startLimit + Math.random() * endLimit );endLimit );

}}

The above function can serve as a The above function can serve as a general purpose randomize function general purpose randomize function that can generate the value between that can generate the value between startLimit and endLimitstartLimit and endLimit

Page 12: Pemrograman Teknologi Internet W06: Functions and Events

12

Variable ScopeVariable Scopevar x = 1; // global variablevar x = 1; // global variable

function start()function start(){{

var x = 5; // variable local to function startvar x = 5; // variable local to function start

functionA(); // functionA has local xfunctionA(); // functionA has local xfunctionB(); // functionB uses global variable xfunctionB(); // functionB uses global variable xfunctionA(); // functionA reinitializes local xfunctionA(); // functionA reinitializes local xfunctionB(); // global variable x retains its valuefunctionB(); // global variable x retains its value

}}

function functionA()function functionA(){{

var x = 25; // initialized each timevar x = 25; // initialized each time}}

function functionB()function functionB(){{

x *= 10;x *= 10;}}

Page 13: Pemrograman Teknologi Internet W06: Functions and Events

13

Recursive FunctionRecursive Function

Consider the following code fragment to Consider the following code fragment to find find n!n!::

function factorial(number) {var f = 1;for ( var counter = number; counter >= 1; --counter ) {

f *= counter;}return f;

}

It can be achieved using recursive:It can be achieved using recursive:n! = n · (n – 1)!

Page 14: Pemrograman Teknologi Internet W06: Functions and Events

14

Recursive FunctionRecursive Function Rewritten using recursion:Rewritten using recursion:

function factorial( number ){

if ( number <= 1 ) // base casereturn 1;

elsereturn number * factorial( number - 1 );

}

Recursive Function Recursive Function Function that can Function that can call itself repeatedlycall itself repeatedly

Page 15: Pemrograman Teknologi Internet W06: Functions and Events

15

Event ModelEvent Model

Dynamic HTML with the event model exists Dynamic HTML with the event model exists so that scripts can respond to user so that scripts can respond to user interactions and change the page interactions and change the page accordingly.accordingly.

This makes Web applications more This makes Web applications more responsive and user-friendly and can reduce responsive and user-friendly and can reduce server load.server load.

With the event model, scripts can respond to a user who is moving the mouse, scrolling up or down the screen or entering keystrokes.

Page 16: Pemrograman Teknologi Internet W06: Functions and Events

16

Form ValuesForm Values Consider the following html code:Consider the following html code:

<form name=“myform” action=“”><form name=“myform” action=“”><input name=“username” type=“text” /><input name=“username” type=“text” /><input name=“password” type=“password” /><input name=“password” type=“password” /><input name=“submit” type=“submit” /><input name=“submit” type=“submit” />

</form></form>

We can access the values using this We can access the values using this syntax:syntax:

var username = document.myform.username.value;var username = document.myform.username.value;var password = document.myform.password.value;var password = document.myform.password.value;

Page 17: Pemrograman Teknologi Internet W06: Functions and Events

17

Event onclickEvent onclick

One of the most common events is onclick When the user clicks the mouse, the

onclick event fires. With JavaScript, we are able to respond to

onclick and other events. There are two ways to handle the event:

Using new notation for and event in script tag Using inline event (recommended for

compatibility)

Page 18: Pemrograman Teknologi Internet W06: Functions and Events

18

Event onclickEvent onclick<script type="text/javascript" for="para" <script type="text/javascript" for="para"

event="onclick">event="onclick"><!--<!--

alert("Hi there");alert("Hi there");// -->// -->

</script></script>…………<p id="para">Click on this text!</p><p id="para">Click on this text!</p>

<!-- You can specify event handlers inline --><!-- You can specify event handlers inline --><form name="myform"><form name="myform"><input type = "button" value = "Click Me!" <input type = "button" value = "Click Me!"

onclick ="alert( 'Hi again' )"/>onclick ="alert( 'Hi again' )"/></form></form>

Page 19: Pemrograman Teknologi Internet W06: Functions and Events

19

Event onclick Event onclick (Recommended)(Recommended)<script type="text/javascript"><script type="text/javascript">

<!--<!--functionfunction showAlert() { showAlert() {alert("Hi there");alert("Hi there");}}// -->// --></script></script></head></head>

<body><body><p onclick="showAlert();">Click on this text!</p><p onclick="showAlert();">Click on this text!</p><a href="#" onclick="showAlert();">My Link</a><br/><a href="#" onclick="showAlert();">My Link</a><br/><form name="myform"><form name="myform"><input type = "button" value = "Click Me!" onclick <input type = "button" value = "Click Me!" onclick

="alert( 'Hi again' )"/>="alert( 'Hi again' )"/></form></form>

Page 20: Pemrograman Teknologi Internet W06: Functions and Events

20

Event onloadEvent onload

The onload event fires whenever an element finishes loading successfully.

Frequently, this event is used in the body element to initiate a script after the page loads into the client.

Examples: The script can be called by the onload Event in body tag, updates a timer that indicates how many seconds have elapsed since the document has been loaded.

Page 21: Pemrograman Teknologi Internet W06: Functions and Events

21

Event onloadEvent onload<script type="text/javascript"><script type="text/javascript">

varvar seconds = 0; seconds = 0;

functionfunction startTimer() { startTimer() {// 1000 milliseconds = 1 second// 1000 milliseconds = 1 secondwindow.setInterval("updateTime()", 1000);window.setInterval("updateTime()", 1000);

}}

functionfunction updateTime() { updateTime() {seconds++;seconds++;

// only on IE// only on IE// soFar.innerText = seconds;// soFar.innerText = seconds;

document.getElementById("soFar").innerHTML = seconds;document.getElementById("soFar").innerHTML = seconds;}}

</script></script></head></head><body onload="startTimer()"><body onload="startTimer()">

<a id="soFar"><strong>0</strong></a><a id="soFar"><strong>0</strong></a></body></body>

Page 22: Pemrograman Teknologi Internet W06: Functions and Events

22

Event onerrorEvent onerror Sometimes scripts refer to objects that

existed at a specified location when the script was written, but the location changes at a later time, rendering your scripts invalid.

The error dialog presented by browsers in such cases can be confusing to the user.

To prevent this dialog box from displaying and to handle errors more elegantly, scripts can use the onerror event to execute specialized error-handling code.

Page 23: Pemrograman Teknologi Internet W06: Functions and Events

23

Event onerrorEvent onerror<script type="text/javascript"><script type="text/javascript">

window.onerror = handleError;window.onerror = handleError;

function doThis() {function doThis() {alrrt("hi"); // alert misspelled, creates an erroralrrt("hi"); // alert misspelled, creates an error

}}

function handleError(errType, errURL, errLineNum) {function handleError(errType, errURL, errLineNum) {var msg = "Error: " + errType + " on line " + errLineNum;var msg = "Error: " + errType + " on line " + errLineNum;document.getElementById('status').innerHTML = msg;document.getElementById('status').innerHTML = msg;

return true;return true;}}</script></script></head></head><body><body>

<input id = "mybutton" type = "button" value = "Click Me!" onclick <input id = "mybutton" type = "button" value = "Click Me!" onclick ="doThis()"/>="doThis()"/>

<p id="status">&nbsp;</p><p id="status">&nbsp;</p></body></body>

Page 24: Pemrograman Teknologi Internet W06: Functions and Events

24

Event onmousemoveEvent onmousemove

This event will be triggered This event will be triggered whenever a mouse is being moved whenever a mouse is being moved within your html document.within your html document.

It can be put inside the body tag, It can be put inside the body tag, similar as event onload.similar as event onload.

Page 25: Pemrograman Teknologi Internet W06: Functions and Events

25

Event onmousemove (IE Event onmousemove (IE only)only)

<script type="text/javascript"><script type="text/javascript">function updateMouseCoordinates() {function updateMouseCoordinates() {

document.getElementById('status').innerHTML = document.getElementById('status').innerHTML = event.srcElement.tagName +event.srcElement.tagName +" (" +" (" +event.offsetX +event.offsetX +", " +", " +event.offsetY +event.offsetY +")";")";

}}</script></script></head></head><body onmousemove ="updateMouseCoordinates()"><body onmousemove ="updateMouseCoordinates()">

<input id = "mybutton" type = "button" value = "Click <input id = "mybutton" type = "button" value = "Click Me!" />Me!" /><p id="status">&nbsp;</p><p id="status">&nbsp;</p>

</body></body>

Page 26: Pemrograman Teknologi Internet W06: Functions and Events

26

Event onfocus & onblurEvent onfocus & onblur

The onfocus and onblur events are particularly useful when dealing with form elements that allow user input

The onfocus event fires when an element gains focus (i.e., when the user clicks a form field or when the user uses the Tab key to move between form elements)

The onblur fires when an element loses focus, which occurs when another control gains the focus

Page 27: Pemrograman Teknologi Internet W06: Functions and Events

27

Event onsubmit & Event onsubmit & onresetonreset

Two more useful events for processing forms are onsubmit and onreset.

These events fire when a form is submitted or reset, respectively.

These events can be put within the <form> tag that enable to catch event whenever submit or reset button is initiated.

To cancel default action:window.event.returnValue = true;

Page 28: Pemrograman Teknologi Internet W06: Functions and Events

28

Event onsubmit & Event onsubmit & onresetonreset

<form id = "myForm" onsubmit = "formSubmit()"onreset = "formReset()" action = "">

Name: <input type = "text" name = "name"onfocus = "helpText(0)" onblur = "helpText(6)" /><br />

Email: <input type = "text" name = "email"onfocus = "helpText(1)" onblur = "helpText(6)" /><br />

Click here if you like this site<input type = "checkbox" name = "like" onfocus ="helpText(2)" onblur = "helpText(6)" /><hr />

…</form>

Page 29: Pemrograman Teknologi Internet W06: Functions and Events

29

Event BubblingEvent Bubbling

Event bubbling, a crucial part of the event model, is the process whereby events fired in child elements also “bubble” up to their parent elements for handling.

If you intend to handle an event in a child element, you might need to cancel the bubbling of that event in that child element’s event-handling code by using the cancelBubble property of the event object

event.cancelBubble = true;

Page 30: Pemrograman Teknologi Internet W06: Functions and Events

30

Other EventsOther Events

Page 31: Pemrograman Teknologi Internet W06: Functions and Events

31

Related Mouse EventsRelated Mouse Events