JavaScript, Part 3 Instructor: Charles Moen CSCI/CINF 4230.

23
JavaScript, Part 3 Instructor: Charles Moen CSCI/CINF 4230

Transcript of JavaScript, Part 3 Instructor: Charles Moen CSCI/CINF 4230.

Page 1: JavaScript, Part 3 Instructor: Charles Moen CSCI/CINF 4230.

JavaScript, Part 3

Instructor: Charles Moen

CSCI/CINF 4230

Page 2: JavaScript, Part 3 Instructor: Charles Moen CSCI/CINF 4230.

2

Events

Events are fired by actions that happen in a document, e.g. a user clicks a button or submits a form

JavaScript programs are event-driven• The program waits for some user action

– Clicking a link or a check box

– Submitting a form

– Loading a page

• An action triggers an event – e.g. click, submit, or load events

• Then a function is executed as a result of the event firing

JavaScript (Koch)

Page 3: JavaScript, Part 3 Instructor: Charles Moen CSCI/CINF 4230.

3

Event Handlers

Event handlers are the functions that are executed when a particular event fires

We add GUI controls and event handlers to a Web page to make it interactive

• The user interacts with a control – e.g., by changing the value in a form field or clicking on a submit button

• The event handler function is notified of this event

• Then the function executes

JavaScript (Koch, Ding)

Page 4: JavaScript, Part 3 Instructor: Charles Moen CSCI/CINF 4230.

4

Some Events

Mouse events are available on all HTML elements Interface events are fired after certain mouse or key actions, e.g., the submit

event fires after a user clicks on a submit button

Mouse events Interface events Keyboard events

click blur keydown

dblclick focus keypress

mousedown change keyup

mousemove load

mouseout unload

mouseover submit

mouseup resize

scroll

JavaScript (Koch, Ding)

Page 5: JavaScript, Part 3 Instructor: Charles Moen CSCI/CINF 4230.

5

Some Commonly Used Events

click• An element is clicked once

mouseover• The mouse moves over an element

change• The value of an element changes

load• A page has been completely loaded in the browser

submit• A user submits a form

JavaScript (Koch, Ding)

Page 6: JavaScript, Part 3 Instructor: Charles Moen CSCI/CINF 4230.

6

A Simple Example

<html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Event Handling Example</title> </head> <body> <form method="post" action="hello.aspx"> <input type="button" value="Click me" onclick="alert('Hello');"/> </form> </body></html>

JavaScript

Add “on” in front of the event name

Page 7: JavaScript, Part 3 Instructor: Charles Moen CSCI/CINF 4230.

7

Event Handler Registration

Method 1: Inline event handlers• Add an attribute to an HTML element

• Works in all browsers

• Deprecated because behaviour is not separated from structure

<form method="GET" action="" onsubmit="addSandwich(this);return false;"></form>

Method 2: Register event handlers in the script• Best practice

JavaScript (Koch)

An inline event handlerAdd “on” in front of the event name

Page 8: JavaScript, Part 3 Instructor: Charles Moen CSCI/CINF 4230.

8

Register Event Handlers in the Script

Event-handling attributes are properties of elements in JavaScript Assign the event handler function to the element’s property for a

particular event

function initForm() { var theForm = document.getElementById("sandwichform"); theForm.onsubmit=addSandwich;}

JavaScript (Koch)

<form method="GET" action="" id="sandwichform">

<!-- more code here -->

</form>

myscripts.js

The property for the submit event The event handler (do not use the parentheses)

Page 9: JavaScript, Part 3 Instructor: Charles Moen CSCI/CINF 4230.

9

The load Event

Fires when the page is completely loaded in the browser Script initialization can be triggered by the load event

JavaScript (Koch)

function initForm() { var theForm = document.getElementById("sandwichform"); theForm.onsubmit=addSandwich;}

window.onload = initForm;

myscripts.js

This assignment is executed immediately, because it is not in a function.

Whenever the load event fires, the initForm function will execute

The event handler (do not use the parentheses)

Page 10: JavaScript, Part 3 Instructor: Charles Moen CSCI/CINF 4230.

10

this

When used inside a function body, “this” refers to the object that the function belongs to

If we assign a function as an object’s event handler, then it belongs to that object

JavaScript (Koch)

function addSandwich() { var mySandwich = ""; for (var i=0; i<this.length; i++) { var element = this.elements[i];

<!-- more code here -->

return false;}

function initForm() { var theForm = document.getElementById("sandwichform"); theForm.onsubmit=addSandwich;}

window.onload = initForm;

Since the “addSandwich” function belongs to the form, we can use “this” to refer to the form itself

When we assigned the function as an event handler of “theForm,” the function became a method of the form object and “belongs” to it.

function addSandwich(mySandwichForm) { var mySandwich = ""; for (var i=0; i<mySandwichForm.length; i++) { var element = mySandwichForm.elements[i];

<!-- more code here -->

}

In the original function, we had to pass the form as an argument

Page 11: JavaScript, Part 3 Instructor: Charles Moen CSCI/CINF 4230.

11

Advanced Event Handler Registration

The script-based event handler registration, as described so far, is considered the “traditional” approach because it is part of the Netscape 3 standard

PROBLEM: • With the traditional approach, only one function can be

registered for any one particular event

Advanced event handler registration allows many event handlers for the same event on the same element

• W3C event handler registration

• Microsoft event handler registration

JavaScript (Koch)

Page 12: JavaScript, Part 3 Instructor: Charles Moen CSCI/CINF 4230.

12

W3C Event Handler Registration

Supported by Mozilla and Safari, but not by Microsoft IE

function initForm() { var theForm = document.getElementById("sandwichform"); theForm.onsubmit=addSandwich;}

window.addEventListener("load",initForm,false);

JavaScript (Koch)

myscripts.js

Use the “addEventListener” method of the object that gets the event handler

Three arguments:

1. The event name as a string

2. The event handler function

3. A boolean

false = the event bubbles up (the usual choice)

true = the event is captured

Page 13: JavaScript, Part 3 Instructor: Charles Moen CSCI/CINF 4230.

13

Microsoft Event Handler Registration

Supported by Microsoft IE, but not Mozilla and Safari

function initForm() { var theForm = document.getElementById("sandwichform"); theForm.onsubmit=addSandwich;}

window.attachEvent("onload",initForm);

JavaScript (Koch)

myscripts.js

Use the “attachEvent” method of the object that gets the event handler

Two arguments:

1. The event name as a string, with “on” in front of the name

2. The event handler function

Page 14: JavaScript, Part 3 Instructor: Charles Moen CSCI/CINF 4230.

14

Cross Browser Support

Browser detection (deprecated)• Check the value of navigator.userAgent, and then branch to handle each

browser differently

• Early technique that is unreliable now, because the userAgent value is unpredictable

JavaScript (Koch)

Object detection• If your script uses an object or method, first check whether it exists in the

browser

• You don’t need to know the browser identity

<html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Event Handling Example</title> <script> document.write(navigator.userAgent); </script> </head> <body> </body></html>

Browser detection scripts attempt to search the value of this property for the name of the browser.

Page 15: JavaScript, Part 3 Instructor: Charles Moen CSCI/CINF 4230.

function initForm() { var theForm = document.getElementById("sandwichform"); theForm.onsubmit=addSandwich;}

if (window.addEventListener) { window.addEventListener("load",initForm,false);}else if (window.attachEvent) { window.attachEvent("onload",initForm);}

myscripts.js

15

Object Detection

If your script uses an object or method, first check whether it exists in the browser; if it doesn’t exist, then return

Works with any browser, any object, any method

JavaScript (Koch)

Testing whether this method exists

Page 16: JavaScript, Part 3 Instructor: Charles Moen CSCI/CINF 4230.

DHTML

Page 17: JavaScript, Part 3 Instructor: Charles Moen CSCI/CINF 4230.

17

DHTML

Dynamic HTML

A buzzword, not a standard• Adding visual effects to Web pages by using JavaScript and the

DOM to change the CSS styles of HTML elements

Some common uses today• Rollover buttons

• Dropdown menus

• Animations

JavaScript (Koch, Wikipedia)

Page 18: JavaScript, Part 3 Instructor: Charles Moen CSCI/CINF 4230.

18

Background About DHTML

First introduced in the Netscape and IE version 4 browsers• The ability to add visual effects to the dynamically was exciting, because

Web pages had always been static documents

• The problem: Most users still had version 3 browsers

Also, Netscape and IE tried to be as incompatible as possible• Browser sniffing was recommended for dealing with incompatibilities

• Hooks to elements were treated differently

JavaScript (Koch, Wikipedia, Yue)

<div id="greeting" style="position:absolute;">Hello</div>

var greetingDiv = document.layers["greeting"];

In Netscape

<div id="greeting">Hello</div>

var greetingDiv = document.all["greeting"];

In IE

Page 19: JavaScript, Part 3 Instructor: Charles Moen CSCI/CINF 4230.

19

A Simple ExampleJavaScript (Koch, Wikipedia, Yue)

<script type="text/javascript">function moveRight(){ var greetingDiv = document.getElementById('greeting'); greetingDiv.style.left='100px';}function makeRed(){ var greetingDiv = document.getElementById('greeting'); greetingDiv.style.color='red';}function makeBold(){ var greetingDiv = document.getElementById('greeting'); greetingDiv.style.fontWeight='bold';}function makeInvisible(){ var greetingDiv = document.getElementById('greeting'); greetingDiv.style.visibility='hidden';}function reset(){ var greetingDiv = document.getElementById('greeting'); greetingDiv.style.left=0; greetingDiv.style.color='black'; greetingDiv.style.fontWeight='normal'; greetingDiv.style.visibility='visible';}</script>

Page 20: JavaScript, Part 3 Instructor: Charles Moen CSCI/CINF 4230.

20

More Examples

http://www.w3schools.com/dhtml/dhtml_examples.asp

JavaScript (W3schools)

Page 21: JavaScript, Part 3 Instructor: Charles Moen CSCI/CINF 4230.

21

innerHTML

A property of an element• All of the HTML in the element

Not part of the DOM

Introduced by Microsoft in IE4, and supported by most browsers today

JavaScript (Keith, Yue)

Page 22: JavaScript, Part 3 Instructor: Charles Moen CSCI/CINF 4230.

<html><head><script>function testInnerHtml() { var emptyDiv = document.getElementById("empty"); emptyDiv.innerHTML = "<p>Some <em>new</em> text.</p>";}</script></head><body><p><a href="#" onclick="testInnerHtml();return false;">Test innerHTML</a></p><div id="empty"></div></body></html>

22

Using innerHTMLJavaScript (Keith, Yue)

Page 23: JavaScript, Part 3 Instructor: Charles Moen CSCI/CINF 4230.

23

References

Ding, Wei, “JavaScript” UHCL lecture slides, 2008.

Keith, Jeremy. DOM Scripting: Web Design with JavaScript and the Document Object Model. friends of ED, 2005.

Koch, Peter-Paul, PPK on JavaScript. New Riders, 2007.

Schultz, David and Craig Cook, Beginning HTML with CSS and XHTML: Modern Guide and Reference. Apress, 2007.

Shannon, Ross. “DHTML Explained”. (2008) [Online]. Available: http://www.yourhtmlsource.com/javascript/dhtmlexplained.html

W3Schools Online Web Tutorials. “JavaScript Tutorial”. [Online]. Available: http://www.w3schools.com/js/default.asp

Wikipedia. “DHTML”. [Online]. Available:http://en.wikipedia.org/wiki/Dynamic_HTML

Yue, Kwok-Bun, “An Introduction to JavaScript” UHCL lecture notes, 2000.

Yue, Kwok-Bun, “An Introduction to Dynamic HTML” UHCL lecture notes, 2000.