jquery : events are where it happens!

38
jQuery: Events are where it happens! Doc. v. 0.1 - 17/03/09 Wildan Maulana | wildan [at] tobethink.com #4

Upload: wildan-maulana

Post on 05-Jul-2015

6.545 views

Category:

Technology


0 download

TRANSCRIPT

Page 1: jQuery : Events are where it happens!

jQuery: Events are where it happens!

Doc. v. 0.1 - 17/03/09

Wildan Maulana | wildan [at] tobethink.com

#4

Page 2: jQuery : Events are where it happens!

What this presentation Covers

• The event models as implemented by the browsers

• Using jQuery to bind event handlers to elements

• The Event object instance

• Triggering event handlers under script control

Page 3: jQuery : Events are where it happens!

The GUI Rule

1.Set up the user interface2.Wait for something interesting to

happen3.React accordingly4.Repeat

Page 4: jQuery : Events are where it happens!

Understanding the browser event model

Page 5: jQuery : Events are where it happens!

The DOM Level 0 Event Model<html> <head> <title>DOM Level 0 Events Example</title> <script type="text/javascript" src="../scripts/jquery-1.2.1.js"> </script> <script type="text/javascript"> $(function(){ $('#vstar')[0].onmouseover = function(event) { say('Whee!'); } });

function say(text) { $('#console').append('<div>'+new Date()+' '+text+'</div>'); } </script> </head>

<body> <img id="vstar" src="vstar.jpg" onclick="say('Vroom vroom!')"/> <div id="console"></div> </body></html>

Ready handlers definesmouseover handlers

Utility function emits textto console

<img> element is instrumented

Ready handlers definesmouseover handlers

<div> element serve asconsole

Page 6: jQuery : Events are where it happens!

Event Handler

onclick="say('Vroom vroom!');"

imageElement.onclick = function(event) {  say('Vroom vroom!');}

an anonymous function is automatically created using the value

of the attribute as the function body

Page 7: jQuery : Events are where it happens!

The DOM Level 0 Event Model In Action

Page 8: jQuery : Events are where it happens!

The Event instance

Page 9: jQuery : Events are where it happens!

Event Bubbling

• What is Event Bubbling ?

Page 10: jQuery : Events are where it happens!

Event Bubbling in Action

• Events propagating from the point of origin to the top of the DOM tree

<html id="greatgreatgrandpa"> <head> <title>DOM Level 0 Bubbling Example</title> <script type="text/javascript" src="../scripts/jquery-1.2.1.js"> </script> <script type="text/javascript"> $(function(){ $('*').each(function(){ var current = this; this.onclick = function(event) { if (!event) event = window.event; var target = (event.target) ? event.target : event.srcElement; say('For ' + current.tagName + '#'+ current.id + ' target is ' + target.id); } }); });

function say(text) { $('#console').append('<div>'+text+'</div>'); } </script> </head>

<body id="greatgrandpa"> <div id="grandpa"> <div id="pops"> <img id="vstar" src="vstar.jpg"/> </div> </div> <div id="console"></div> </body></html>

Page 11: jQuery : Events are where it happens!

Affecting event propagation

• If we want to prevent an event from propagating, we can use : – stopPropagation() method of the Event

instance (for standard compliant browser) or

– In internet explore, we set a property named cancelBubble to true in the Event instance

Page 12: jQuery : Events are where it happens!

Lack of DOM Level 0• One severe shortcoming of the DOM Level 0 Event Model is

that, because a property is used to store a reference to a function that’s to serve as an event handler,only one event handler per element can be registered for any specific event type

someElement.onclick = doFirstThing;someElement.onclick = doSecondThing;

Won't work !

• Using Observable pattern that establishes a publish/subscribe schema for that handlers• Or using closure Or …• Using DOM Level 2 Event Model

The solution

Page 13: jQuery : Events are where it happens!

The DOM Level 2 Event Model

Page 14: jQuery : Events are where it happens!

Establishing events

• Rather than assigning a function reference to an element property, DOM Level 2 event handlers—also termed listeners—are established via an element method.

• Each DOM element defines a method named addEventListener() that’s used to attach event handlers (listeners) to the element

addEventListener(eventType,listener,useCapture)

Page 15: jQuery : Events are where it happens!

addEventListener()

addEventListener(eventType,listener,useCapture)

EventType is a string that identifies the type of event to be handled

The listener parameter is a referenceto the function (or inline function) that’s to be established as the handler for the named event type on the element

useCapture, is a Boolean

Page 16: jQuery : Events are where it happens!

Establishing event handlers with the DOM Level 2 Model

<html> <head> <title>DOM Level 2 Events Example</title> <script type="text/javascript" src="../scripts/jquery-1.2.1.js"> </script> <script type="text/javascript"> $(function(){ var element = $('#vstar')[0]; element.addEventListener('click',function(event) { say('Whee once!'); },false); element.addEventListener('click',function(event) { say('Whee twice!'); },false); element.addEventListener('click',function(event) { say('Whee three times!'); },false); });

function say(text) { $('#console').append('<div>'+text+'</div>'); } </script> </head> <body> <img id="vstar" src="vstar.jpg"/> <div id="console"></div> </body></html>

Remember : The Order of the execution is not guaranteed ! It can be random !

Page 17: jQuery : Events are where it happens!

Event Propagation

Propagation in the DOM Level 2 Event Model traverses the DOMhierarchy twice: once from top to target during capture phase and once from target to top during bubble phase.

Page 18: jQuery : Events are where it happens!

Tracking event propagation with bubble and capture handlers

<html id="greatgreatgrandpa"> <head> <title>DOM Level 2 Propagation Example</title> <script type="text/javascript" src="../scripts/jquery-1.2.1.js"> </script> <script type="text/javascript"> $(function(){ $('*').each(function(){ var current = this; this.addEventListener('click',function(event) { say('Capture for ' + current.tagName + '#'+ current.id + ' target is ' + event.target.id); },true); this.addEventListener('click',function(event) { say('Bubble for ' + current.tagName + '#'+ current.id + ' target is ' + event.target.id); },false); }); });

function say(text) { $('#console').append('<div>'+text+'</div>'); } </script> </head>

<body id="greatgrandpa"> <div id="grandpa"> <div id="pops"> <img id="vstar" src="vstar.jpg"/> </div> </div> <div id="console"></div> </body></html>

Page 19: jQuery : Events are where it happens!

The Internet Explore Event Model

• Internet Explorer (both IE6 and, most disappointingly, IE7) doesn’t provide support for the DOM Level 2 Event

addEventListener() → attachEvent(eventName,handler)

Page 20: jQuery : Events are where it happens!

The jQuery Event ModeljQuery event implementation

• jQuery event implementation, exhibits the following features :

– Provides a unified method for establishing event handlers

– Allows multiple handlers for each event type on each element

– Uses standard event-type names: for example, click or mouseover

– Makes the Event instance available as a parameter to the handlers

– Normalizes the Event instance for the most often used properties

– Provides unified methods for event canceling and default action blocking

Page 21: jQuery : Events are where it happens!

Binding event handlers using jQuery

• Using the jQuery Event Model, we can establish event handlers on DOM elements with the bind() command :

$('img').bind('click',function(event){alert('Hi there!');});

Page 22: jQuery : Events are where it happens!

Command syntax : bindbind(eventType,data,listener)

Establishes a function as the event handler for the specified event type on all elements in the matched set.

Parameters

eventType (String) Specifies the name of the event type for which the handler is to be established. This event type can be namespaced with a suffix separatedfrom the event name with a period character. See the remainder of thissection for details.

data (Object) Caller-supplied data that’s attached to the Event instance as aproperty named data for availability to the handler functions. If omitted, thehandler function can be specified as the second parameter.

listener (Function) The function that’s to be established as the event handler.

Returns

The wrapped set

Page 23: jQuery : Events are where it happens!

bind() in action<html> <head> <title>jQuery Events Example</title> <script type="text/javascript" src="../scripts/jquery-1.2.1.js"> </script> <script type="text/javascript"> $(function(){ $('#vstar') .bind('click',function(event) { say('Whee once!'); }) .bind('click',function(event) { say('Whee twice!'); }) .bind('click',function(event) { say('Whee three times!'); }); });

function say(text) { $('#console').append('<div>'+text+'</div>'); } </script> </head>

<body> <img id="vstar" src="vstar.jpg"/> <div id="console"></div> </body></html>

Page 24: jQuery : Events are where it happens!

Also works on IE ...

Page 25: jQuery : Events are where it happens!

Command syntax : specific event binding

eventTypeName(listener)

Establishes the specified function as the event handler for the event type named by the method’s name. The supported commands are as follows:● blur● change● click● dblclick● error

● focus● keydown● keypress● keyup● load

● mousedown● mousemove● mouseout● mouseover● mouseup

● resize● scroll● select● submit● unload

Note that when using these shortcut methods, we cannot specify a data value to be placed in the event.data property.

Parameters

listener (Function) The function that’s to be established as the event handler.

Returns

The wrapped set.

Page 26: jQuery : Events are where it happens!

Command syntax: one

one(eventType,data,listener)

Establishes a function as the event handler for the specified event type on all elements in the matched set. Once executed, the handler is automatically removed.

Parameters

eventType (String) Specifies the name of the event type for which the handler is to be established.

data (Object) Caller-supplied data that’s attached to the Event instance for availability to the handler functions. If omitted, the handler function can be specified as the second parameter.

listener (Function) The function that’s to be established as the event handle

Returns

The wrapped set.

Page 27: jQuery : Events are where it happens!

Removing event handlersCommand syntax: unbind

unbind(eventType,listener)unbind(event)

Removes events handlers from all elements of the wrapped set as specified by the optional passed parameters. If no parameters are provided, all listeners are removed from the elements.

Parameters

eventType (String) If provided, specifies that only listeners established for the specified event type are to be removed.

listener (Function) If provided, identifies the specific listener that’s to be remove

event (Event) Removes the listener that triggered the event described by this Event instance.

Returns

The wrapped set.

Page 28: jQuery : Events are where it happens!

Inspecting the Event instanceProperty Description

altKey Set to true if the Alt key was pressed when the event was triggered, false if not. The Alt key is labeled Option on most Mac keyboards.

ctrlKey Set to true if the Ctrl key was pressed when the event was triggered, false if not.

data The value, if any, passed as the second parameter to the bind() command when thehandler was established.

keyCode For keyup and keydown events, this returns the key that was pressed. Note that for alphabetic characters, the uppercase version of the letter will be returned, regardless of whether the user typed an uppercase or lowercase letter. For example, both a and A will return 65. You can use shiftKey to determine which case was entered. For keypress events, use the which property, which is reliable across browsers.

Page 29: jQuery : Events are where it happens!

Inspecting the Event instance

metaKey Set to true if the Meta key was pressed when the event was triggered, false if not.The Meta key is the Ctrl key on PCs and the Command key on Macs.

pageX For mouse events, specifies the horizontal coordinate of the event relative from the page origin.

pageY For mouse events, specifies the vertical coordinate of the event relative from the page origin.

relatedTarget For some mouse events, identifies the element that the cursor left or entered when the event was triggered.

screenX For mouse events, specifies the horizontal coordinate of the event relative from the screen origin.

screenY For mouse events, specifies the vertical coordinate of the event relative from the screen origin.

Page 30: jQuery : Events are where it happens!

Inspecting the Event instance

shiftKey Set to true if the Shift key was pressed when the event was triggered, false if not.

target Identifies the element for which the event was triggered.

type For all events, specifies the type of event that was triggered (for example, click). This can be useful if you’re using one event handler function for multiple events.

which For keyboard events, specifies the numeric code for the key that caused the event,and for mouse events, specifies which button was pressed (1 for left, 2 for middle, 3 for right). This should be used instead of button, which can’t be relied on to function consistently across browsers.

Page 31: jQuery : Events are where it happens!

Affecting the event propagation

• stopPropagation() : Prevent the event from bubbling further up the DOM tree

• preventDefault() : cancel any semantic action

that the event might cause

Page 32: jQuery : Events are where it happens!

Triggering event handlersCommand syntax: trigger

trigger(eventType)

Invokes any event handlers established for the passed event type for all matched elements

Parameters

eventType (String) Specifies the name of the event type for handlers which are to be invoked

Returns

The wrapped set

Page 33: jQuery : Events are where it happens!

Command syntax: eventName

eventName()

Invokes any event handlers established for the named event type for all matched elements.

The supported commands are as follows:

● blur● click ● focus ● select● submit

Parameters

none

Returns

The wrapped set.

Page 34: jQuery : Events are where it happens!

Other event-related commands

• Toggling listener

Page 35: jQuery : Events are where it happens!

Command syntax: toggle

toggle(listenerOdd,listenerEven)

Establishes the passed functions as click event handlers on all elements of the wrapped set that toggle between each other with every other trigger of a click event

Parameters

listenerOdd (Function) A function that serves as the click event handler for all odd-numbered clicks (the first, the third, the fifth, and so on)

listenerEven (Function) A function that serves as the click event handler for all even-numbered clicks (the second, the fourth, the sixth, and so on)

Returns

The wrapped set

Page 36: jQuery : Events are where it happens!

toggle()<html> <head> <title>jQuery Toggle Command Example</title> <script type="text/javascript" src="../scripts/jquery-1.2.1.js"> </script> <script type="text/javascript"> $(function(){ $('#vstar').toggle( function(event) { $(event.target).css('opacity',0.4); }, function(event) { $(event.target).css('opacity',1.0); } ); }); </script> </head>

<body> <img id="vstar" src="vstar.jpg"/> </body></html>

Page 37: jQuery : Events are where it happens!

TODO

Page 38: jQuery : Events are where it happens!

Reference

• jQuery in Action, Bear Bibeault, Yehuda Katz, Manning