Presentation is loading. Please wait.

Presentation is loading. Please wait.

Pemrograman Teknologi Internet W06: Functions and Events.

Similar presentations


Presentation on theme: "Pemrograman Teknologi Internet W06: Functions and Events."— Presentation transcript:

1 Pemrograman Teknologi Internet W06: Functions and Events

2 2 Objectives Functions Functions User-defined Functions User-defined Functions Event Handling Event Handling

3 3 Function Introduction Experience has shown that the best way to develop and maintain a large program is to construct it from small, simple pieces, or modules. Experience has shown that the best way to develop and maintain a large program is to construct it from small, 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”.

4 4 Function Introduction function function-name( parameter-list ) { declarations and statements } Modules in JavaScript are called functions. Modules in JavaScript are called functions. JavaScript programs are written by combining new functions that the programmer writes with “prepackaged” functions and objects available in JavaScript. JavaScript programs are written by combining new functions that the programmer writes with “prepackaged” functions and objects available in JavaScript. The prepackaged functions that belong to JavaScript objects (such as Math.pow and Math.round, introduced previously) are often called methods The prepackaged functions that belong to JavaScript objects (such as Math.pow and Math.round, introduced previously) are often called methods

5 5 Worker-Function Relationship  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.

6 6 Function 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 ) + " " ); } // The following square function's body is executed // only when the function is explicitly called. // square function definition function square( y ) { return y * y; }

7 7 Function Definition function square( y ) { return y * y; } The definition of function square shows that square expects a single parameter y. The definition of function square shows that square expects a single parameter y. Function square uses this name in its body to manipulate the value passed to square from line 20. Function square uses this name in its body to manipulate the value passed to square from line 20. The return statement in square passes the result of the calculation y * y back to the calling function. The return statement in square passes the result of the calculation y * y back to the calling function. Note: JavaScript keyword var is not used to declare variables in the parameter list of a function. Note: JavaScript keyword var is not used to declare variables in the parameter list of a function.

8 8 Return 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 ) ); }

9 9 Math.random() General Use: General Use: var randomValue = Math.random(); Method random generates a floating-point value from 0.0 up to, but not including, 1.0. Method random generates a floating-point value from 0.0 up to, but not including, 1.0. If random truly produces values at random, then every value from 0.0 up to, but not including, 1.0 has an equal chance (or probability) of being chosen each time random is called If random truly produces values at random, then every value from 0.0 up to, but not including, 1.0 has an equal chance (or probability) of being chosen each time random is called Example: Example: var x = Math.floor( 1 + Math.random() * 6 );

10 10 Global vs Method (Object 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.

11 11 How to wrap up as a function? function Random(startLimit, endLimit) { return Math.floor( startLimit + Math.random() * endLimit ); } The above function can serve as a general purpose randomize function that can generate the value between startLimit and endLimit The above function can serve as a general purpose randomize function that can generate the value between startLimit and endLimit

12 12 Variable Scope var x = 1; // global variable function start() { var x = 5; // variable local to function start functionA(); // functionA has local x functionB(); // functionB uses global variable x functionA(); // functionA reinitializes local x functionB(); // global variable x retains its value } function functionA() { var x = 25; // initialized each time } function functionB() { x *= 10; }

13 13 Recursive Function Consider the following code fragment to find n!: Consider the following code fragment to find 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)!

14 14 Recursive Function Rewritten using recursion: Rewritten using recursion: function factorial( number ) { if ( number <= 1 ) // base case return 1; else return number * factorial( number - 1 ); } Recursive Function  Function that can call itself repeatedly Recursive Function  Function that can call itself repeatedly

15 15 Event Model Dynamic HTML with the event model exists so that scripts can respond to user interactions and change the page accordingly. Dynamic HTML with the event model exists so that scripts can respond to user interactions and change the page accordingly. This makes Web applications more responsive and user-friendly and can reduce server load. This makes Web applications more responsive and user-friendly and can reduce 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.

16 16 Form Values Consider the following html code: Consider the following html code: </form> We can access the values using this syntax: We can access the values using this syntax: var username = document.myform.username.value; var password = document.myform.password.value;

17 17 Event 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)

18 18 Event onclick <!-- alert("Hi there"); // --> </script>…… Click on this text! Click on this text! <input type = "button" value = "Click Me!" onclick ="alert( 'Hi again' )"/> </form>

19 19 Event onclick (Recommended) <!-- function showAlert() { alert("Hi there"); } // --> </script></head><body> Click on this text! Click on this text! My Link My Link </form>

20 20 Event 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.

21 21 Event onload var seconds = 0; function startTimer() { // 1000 milliseconds = 1 second window.setInterval("updateTime()", 1000); } function updateTime() { seconds++; // only on IE // soFar.innerText = seconds; document.getElementById("soFar").innerHTML = seconds; }</script></head> 0 0 </body>

22 22 Event 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.

23 23 Event onerror window.onerror = handleError; function doThis() { alrrt("hi"); // alert misspelled, creates an error } function handleError(errType, errURL, errLineNum) { var msg = "Error: " + errType + " on line " + errLineNum; document.getElementById('status').innerHTML = msg; return true; }</script></head><body> </body>

24 24 Event onmousemove This event will be triggered whenever a mouse is being moved within your html document. This event will be triggered whenever a mouse is being moved within your html document. It can be put inside the body tag, similar as event onload. It can be put inside the body tag, similar as event onload.

25 25 Event onmousemove (IE only) function updateMouseCoordinates() { document.getElementById('status').innerHTML = event.srcElement.tagName + " (" + event.offsetX + ", " + event.offsetY + ")";}</script></head> </body>

26 26 Event 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

27 27 Event onsubmit & onreset 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 tag that enable to catch event whenever submit or reset button is initiated. To cancel default action: window.event.returnValue = true;

28 28 Event onsubmit & onreset <form id = "myForm" onsubmit = "formSubmit()" onreset = "formReset()" action = ""> Name: <input type = "text" name = "name" onfocus = "helpText(0)" onblur = "helpText(6)" /> Email: <input type = "text" name = "email" onfocus = "helpText(1)" onblur = "helpText(6)" /> Click here if you like this site <input type = "checkbox" name = "like" onfocus = "helpText(2)" onblur = "helpText(6)" /> …

29 29 Event 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;

30 30 Other Events

31 31 Related Mouse Events


Download ppt "Pemrograman Teknologi Internet W06: Functions and Events."

Similar presentations


Ads by Google