jQuery : Events are where it happens!
Upcoming SlideShare
Loading in...5
×
 

jQuery : Events are where it happens!

on

  • 10,765 views

 

Statistics

Views

Total Views
10,765
Views on SlideShare
10,701
Embed Views
64

Actions

Likes
5
Downloads
75
Comments
2

3 Embeds 64

http://www.slideshare.net 58
http://wildanm.wordpress.com 5
http://www.scoop.it 1

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

jQuery : Events are where it happens! jQuery : Events are where it happens! Presentation Transcript

  • #4 jQuery: Events are where it happens! Doc. v. 0.1 - 17/03/09 Wildan Maulana | wildan [at] tobethink.com
  • 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
  • The GUI Rule 1.Set up the user interface 2.Wait for something interesting to happen 3.React accordingly 4.Repeat
  • Understanding the browser event model
  • The DOM Level 0 Event Model <html> <head> <title>DOM Level 0 Events Example</title> <script type=quot;text/javascriptquot; src=quot;../scripts/jquery-1.2.1.jsquot;> Ready handlers defines </script> mouseover handlers <script type=quot;text/javascriptquot;> $(function(){ $('#vstar')[0].onmouseover = function(event) { say('Whee!'); Utility function emits text } to console }); function say(text) { $('#console').append('<div>'+new Date()+' '+text+'</div>'); } <div> element serve as </script> console <img> element is instrumented </head> <body> <img id=quot;vstarquot; src=quot;vstar.jpgquot; onclick=quot;say('Vroom vroom!')quot;/> <div id=quot;consolequot;></div> </body> </html>
  • Event Handler onclick=quot;say('Vroom vroom!');quot; an anonymous function is automatically created using the value of the attribute as the function body imageElement.onclick = function(event) {   say('Vroom vroom!'); }
  • The DOM Level 0 Event Model In Action
  • The Event instance
  • Event Bubbling • What is Event Bubbling ?
  • Event Bubbling in Action <html id=quot;greatgreatgrandpaquot;> <head> <title>DOM Level 0 Bubbling Example</title> <script type=quot;text/javascriptquot; src=quot;../scripts/jquery-1.2.1.jsquot;> Events propagating • </script> from the point of origin to the <script type=quot;text/javascriptquot;> $(function(){ top of the $('*').each(function(){ DOM tree 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=quot;greatgrandpaquot;> <div id=quot;grandpaquot;> <div id=quot;popsquot;> <img id=quot;vstarquot; src=quot;vstar.jpgquot;/> </div> </div> <div id=quot;consolequot;></div> </body> </html>
  • 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
  • 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 The solution a publish/subscribe schema for that handlers • Or using closure Or … • Using DOM Level 2 Event Model
  • The DOM Level 2 Event Model
  • 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)
  • addEventListener() addEventListener(eventType,listener,useCapture) EventType is a string that identifies the type of event to be handled useCapture, is a Boolean The listener parameter is a reference to the function (or inline function) that’s to be established as the handler for the named event type on the element
  • Establishing event handlers with the DOM Level 2 Model <html> <head> <title>DOM Level 2 Events Example</title> <script type=quot;text/javascriptquot; src=quot;../scripts/jquery-1.2.1.jsquot;> </script> <script type=quot;text/javascriptquot;> $(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=quot;vstarquot; src=quot;vstar.jpgquot;/> Remember : The Order of the execution <div id=quot;consolequot;></div> is not guaranteed ! It can be random ! </body> </html>
  • Event Propagation Propagation in the DOM Level 2 Event Model traverses the DOM hierarchy twice: once from top to target during capture phase and once from target to top during bubble phase.
  • <html id=quot;greatgreatgrandpaquot;> Tracking event propagation <head> with bubble and capture handlers <title>DOM Level 2 Propagation Example</title> <script type=quot;text/javascriptquot; src=quot;../scripts/jquery-1.2.1.jsquot;> </script> <script type=quot;text/javascriptquot;> $(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=quot;greatgrandpaquot;> <div id=quot;grandpaquot;> <div id=quot;popsquot;> <img id=quot;vstarquot; src=quot;vstar.jpgquot;/> </div> </div> <div id=quot;consolequot;></div> </body> </html>
  • 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)
  • The jQuery Event Model jQuery 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
  • 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!');});
  • Command syntax : bind bind(eventType,data,listener) Establishes a function as the event handler for the specified event type on all elements in the matched set. Parameters (String) Specifies the name of the event type eventType for which the handler is to be established. This event type can be namespaced with a suffix separated from the event name with a period character. See the remainder of this section for details. (Object) Caller-supplied data that’s attached data to the Event instance as a property named data for availability to the handler functions. If omitted, the handler function can be specified as the second parameter. (Function) The function that’s to be listener established as the event handler. Returns The wrapped set
  • <html> bind() in action <head> <title>jQuery Events Example</title> <script type=quot;text/javascriptquot; src=quot;../scripts/jquery-1.2.1.jsquot;> </script> <script type=quot;text/javascriptquot;> $(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=quot;vstarquot; src=quot;vstar.jpgquot;/> <div id=quot;consolequot;></div> </body> </html>
  • Also works on IE ...
  • 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 focus mousedown resize ● ● ● ● ● change ● keydown ● mousemove ● scroll ● click ● keypress ● mouseout ● select ● dblclick ● keyup ● mouseover ● submit ● error ● load ● mouseup ● unload Note that when using these shortcut methods, we cannot specify a data value to be placed in the event.data property. Parameters (Function) The function that’s to be established as the listener event handler. Returns The wrapped set.
  • 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.
  • Removing event handlers Command 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.
  • Inspecting the Event instance Property Description Set to true if the Alt key was pressed when the altKey event was triggered, false if not. The Alt key is labeled Option on most Mac keyboards. Set to true if the Ctrl key was pressed when the ctrlKey event was triggered, false if not. The value, if any, passed as the second data parameter to the bind() command when the handler was established. For keyup and keydown events, this returns the keyCode 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.
  • 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.
  • Inspecting the Event instance Set to true if the Shift key was pressed shiftKey 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.
  • 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
  • Triggering event handlers Command 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
  • 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.
  • Other event-related commands • Toggling listener
  • 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
  • toggle() <html> <head> <title>jQuery Toggle Command Example</title> <script type=quot;text/javascriptquot; src=quot;../scripts/jquery-1.2.1.jsquot;> </script> <script type=quot;text/javascriptquot;> $(function(){ $('#vstar').toggle( function(event) { $(event.target).css('opacity',0.4); }, function(event) { $(event.target).css('opacity',1.0); } ); }); </script> </head> <body> <img id=quot;vstarquot; src=quot;vstar.jpgquot;/> </body> </html>
  • TODO
  • Reference • jQuery in Action, Bear Bibeault, Yehuda Katz, Manning