Pemrograman Teknologi Internet W06: Functions and Events.

Slides:



Advertisements
Similar presentations
1 CSC 551: Web Programming Spring 2004 client-side programming with JavaScript  scripts vs. programs  JavaScript vs. JScript vs. VBScript  common tasks.
Advertisements

1 Programmer-Defined Functions Functions allow program modularization Variables declared in function are local variables Only known inside function in.
Session 11 Dynamic HTML: Event Model and Filters Matakuliah: M0114/Web Based Programming Tahun: 2005 Versi: 5.
The Web Warrior Guide to Web Design Technologies
JavaScript Forms Form Validation Cookies. What JavaScript can do  Control document appearance and content  Control the browser  Interact with user.
JavaScript Part for Repetition Statement for statement Cpecifies each of the items needed for counter-controlled repetition with a control variable.
Chapter 7 © 2001 by Addison Wesley Longman, Inc. 1 Chapter 7 Sebesta: Programming the World Wide Web.
Page 1 of 39 Javascript Chapters 13, 14 Vadim Parizher Computer Science Department California State University, Northridge Fall 2003 Slides from text Book.
Outline IS400: Development of Business Applications on the Internet Fall 2004 Instructor: Dr. Boris Jukic JavaScript: Functions Part I.
Lesson 2 Event Handling. Object Event Handlers Most of the objects that make up the Document Object Model respond to asynchronous, user generated events.
1 JavaScript/Jscript 4 Functions. 2 Introduction Programs that solve real-world programs –More complex than programs from previous chapters Best way to.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Events.
 2004 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3.
Introduction to scripting
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 11 – JavaScript/Jscript: Functions Outline 11.1Introduction 11.2Program Modules in JavaScript.
1 CS101 Introduction to Computing Lecture 32 Event Handling (Web Development Lecture 11)
CP476 Internet Computing JavaScript and HTML1 1.JavaScript Execution Environment The JavaScript Window object represents the window in which the browser.
CNIT 133 Interactive Web Pags – JavaScript and AJAX Event and Event Handling.
Event Handlers CS101 Introduction to Computing. Learning Goals Learn about event handlers Determine how events are useful in JavaScript Discover where.
CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Environment.
1 JavaScript: Event Model November 1, 2005 Slides modified from Internet & World Wide Web: How to Program (3rd) edition. By Deitel, Deitel, and Goldberg.
CSS Class 7 Add JavaScript to your page Add event handlers Validate a form Open a new window Hide and show elements Swap images Debug JavaScript.
 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 13 - Dynamic HTML: Object Model and Collections Outline 13.1 Introduction 13.2 Object Referencing.
1 Dynamic HTML III: Event Model Introduction Event model –Scripts respond to user actions and change page accordingly Moving mouse Scrolling screen.
JavaScript: Functions © by Pearson Education, Inc. All Rights Reserved.
 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3.
INTRODUCTION TO JAVASCRIPT AND DOM Internet Engineering Spring 2012.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 16 – Dynamic HTML: Event Model Outline 16.1Introduction 16.2Event ONCLICK 16.3Event ONLOAD.
 2004 Prentice Hall, Inc. All rights reserved. Chapter 14 - Dynamic HTML: Event Model Outline 14.1 Introduction 14.2 Event onclick 14.3 Event onload 14.4.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Functions.
Javascript II DOM & JSON. In an effort to create increasingly interactive experiences on the web, programmers wanted access to the functionality of browsers.
CO1552 Web Application Development HTML Forms, Events and an introduction to JavaScript.
 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 14 - Dynamic HTML: Event Model Outline 14.1 Introduction 14.2 Event onclick 14.3 Event onload.
 2001 Deitel & Associates, Inc. All rights reserved. 1 Outline 16.1Introduction 16.2Program Modules in JavaScript 16.3Programmer-Defined Functions 16.4Function.
Chapter 14: Dynamic HTML: Event Model Presented by: Colbie Brown CS340 Java Web Development Dr. Gloria Carter Love.
Event JavaScript's interaction with HTML is handled through events that occur when the user or browser manipulates a page. When the page loads, that is.
Internet & World Wide Web How to Program, 5/e. © by Pearson Education, Inc. All Rights Reserved.
Chapter 2: Variables, Functions, Objects, and Events JavaScript - Introductory.
Internet & World Wide Web How to Program, 5/e. © by Pearson Education, Inc. All Rights Reserved. 2 Revised by Dr. T. Tran for CSI3140.
JavaScript, Fourth Edition
Chapter 10: JavaScript Functions CIS 275—Web Application Development for Business I.
Introduction to DHTML. What is DHTML? Dynamic HTML Just as Access is Dynamic Database environment Can have controls that respond to events Can have centralized.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 16 – Dynamic HTML: Event Model Outline 16.1Introduction 16.2Event ONCLICK 16.3Event ONLOAD.
 2003 Prentice Hall, Inc. All rights reserved. Chapter 14 - Dynamic HTML: Event Model Outline 14.1 Introduction 14.2 Event onclick 14.3 Event onload 14.4.
 2004 Prentice Hall, Inc. All rights reserved. 1 Segment – 4 Dynamic HTML & CSS.
1 CSC160 Chapter 7: Events and Event Handlers. 2 Outline Event and event handlers onClick event handler onMouseOver event handler onMouseOut event handler.
Event Handling. Objectives Using event handlers Simulating events Using event-related methods.
Project 8: Reacting to Events Essentials for Design JavaScript Level One Michael Brooks.
JavaScript: Functions © by Pearson Education, Inc. All Rights Reserved.
7. JavaScript Events. 2 Motto: Do you think I can listen all day to such stuff? –Lewis Carroll.
Understanding JavaScript and Coding Essentials Lesson 8.
JavaScript II ECT 270 Robin Burke. Outline Functions Events and event handling Form validation.
JavaScript Event Handlers. Introduction An event handler executes a segment of a code based on certain events occurring within the application, such as.
LESSON : EVENTS AND FORM VALIDATION -JAVASCRIPT. EVENTS CLICK.
 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 14 - Dynamic HTML: Event Model Outline 14.1 Introduction 14.2 Event onclick 14.3 Event onload.
JavaScript Events Java 4 Understanding Events Events add interactivity between the web page and the user You can think of an event as a trigger that.
JavaScript Events. Understanding Events Events add interactivity between the web page and the user Events add interactivity between the web page and the.
Jozef Goetz contribution, © by Pearson Education, Inc. All Rights Reserved.
Introduction to JavaScript Events Instructor: Sergey Goldman 1.
REEM ALMOTIRI Information Technology Department Majmaah University.
Introduction to JavaScript Events
Chapter 14: DHTML: Event Model
JavaScript: Functions
JavaScript Functions.
Chapter 10 - JavaScript: Functions
Chapter 14 - Dynamic HTML: Event Model
Chapter 14 - Dynamic HTML: Event Model
13 JavaScript: Events.
Chapter 14 - Dynamic HTML: Event Model
JavaScript and Ajax (JavaScript Events)
Presentation transcript:

Pemrograman Teknologi Internet W06: Functions and Events

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

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

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 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 Event onsubmit & onreset <form id = "myForm" onsubmit = "formSubmit()" onreset = "formReset()" action = ""> Name: <input type = "text" name = "name" onfocus = "helpText(0)" onblur = "helpText(6)" /> <input type = "text" name = " " 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 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 Other Events

31 Related Mouse Events