SlideShare une entreprise Scribd logo
1  sur  39
Télécharger pour lire hors ligne
The Fine Art of JavaScript
Event Handling
Yorick Phoenix
slides: bit.ly/FineArtJSEvents
yorick@issio.net
about.me/yorickphoenix | @scribblings | github.com/yphoenix
General Dev. Philosophy
• Nothing is ever what it seems.
• Expect the unexpected.
• Code Defensively.
• Use Good Tools

(build them if you need to).
Quick Event Recap
• User interaction creates events.
• Which event depends on the element and the
action.
• DOM Level 0 and DOM Level 2 Models.
• Legacy IE and DOM Event Models.
• jQuery is your friend.
abort
afterscriptexecute
animatiend
animatiiterati
animatistart
autocomplete
autocompleteerror
beforecopy
beforecut
beforepaste
beforescriptexecute
beforeunload
blur
cancel
canplay
canplaythrough
change
click
close
copy
ctextmenu
cuechange
cut
dblclick
drag
dragend
dragenter
dragleave
dragover
dragstart
drop
duratichange
emptied
ended
error
focus
hashchange
input
invalid
keydown
keypress
keyup
load
loadeddata
loadedmetadata
loadstart
message
mousedown
mouseenter
mouseleave
mousemove
mouseout
mouseover
mouseup
mousewheel
offline
online
pagehide
pageshow
paste
pause
play
playing
popstate
progress
ratechange
reset
resize
scroll
search
seeked
seeking
select
selectstart
show
stalled
storage
submit
suspend
timeupdate
toggle
transitiend
unload
volumechange
waiting
wheel
etc …
DOM 0
<button onclick="alert('Hello, World!')">
Click Me!
</button>
https://jsfiddle.net/hhj9uu8x/
• No separation of UI and Event handling.
• Of limited use due to limited power, flexibility
and scaleability.
DOM 2 & 3
<button id="moon">Click Me!</button>
$('#moon').click(
function(evt)
{
alert("Hello, world");
});
https://jsfiddle.net/0dqc9s8p/
<Element>
mouseenter
mousemove
mouseleave
mousedown
[blur]
[focusout]
[focus]
[focusin]
mouseup
click
event caveats
• Don't expect to get the events in the same
order.
• Don't expect to get all of the same events.
• Don't expect the fields of the event object
to be complete or correct.
• Each Browser / platform / version writes
their own rules.
Not Sure which events?
TRY IT
EXPERIMENT
detecting user hit
• Don't look at mousedown or mouseup
events.
• look for 'click' events.
• This works for touch devices.
• This works for assisted devices.
click event gotchas
• disabled buttons receive clicks in IE
• readonly text fields get click events
• readonly or disabled div elements get
click events
detecting content change
• Don't look at click, keydown, keyup,
keypress, etc events.
• look for 'change' or 'input' events.
• This works for touch devices.
• This works for assisted devices.
input vs change
• input events indicate that an element
received some input somehow.
• a change event (normally) indicates that
an element has finished changing.
• change events often fire after loss of
focus.
input event gotchas
• checkboxes don't get input events
• input type="file" // receives input events
in IE
• Editable Divs don't get input events in IE
but do everywhere else, you have to use
keyPress too (ugh)
change event gotchas
• unset radio buttons don't get a change
event
• some elements send an input and
change event for every user input
• input type="date" or "time"
• input type="range" // Firefox only
touch events
• Get mapped to mouse & click events
• touchstart, touchmove, touchend
• mouseover, mousemove, mousedown,
mouseup, click
• 300ms delay
avoiding the 300ms delay
• <meta name="viewport"

content="width=device-width, user-scalable=no">
• Handle touchstart, touchmove, touchend events
• Use a library: FTLabs FastClick or Tappy
• http://www.sitepoint.com/5-ways-prevent-300ms-
click-delay-mobile-devices/
too many event handlers?
• if you had a grid of 100 elements and wanted to
detect a click on each element?
• How many event handlers would you need?
<div id="box">
<div class=tile>0</div>
<div class=tile>1</div>
<div class=tile>2</div>
…
<div class=tile>99</div>
</div>
too many event handlers?
$('.tile').click(
function()
{
alert($(this).text());
});
• 100 click handlers, one for every Tile Element.
<div id="box">
<div class=tile>0</div>
<div class=tile>1</div>
<div class=tile>2</div>
…
<div class=tile>99</div>
</div>
• How many does this install?
event bubbling is better
$('.box').on('click',
function(evt)
{
alert($(evt.target).text());
});
• One event handler on the surrounding box element.
<div id="box">
<div class=tile>0</div>
<div class=tile>1</div>
<div class=tile>2</div>
…
<div class=tile>99</div>
</div>
• How many does this install?
event bubbling?
• All events are targeted at an element.
• If that element doesn't have an event handler (that
completely handles the event).
• The event is offered to event handlers of the parent
element, and its parent, etc.
• Until the top of the hierarchy is reached (document)
• Or an event handler indicates that bubbling should
stop.
bubble example?
• a click on a tile sends a click event to the event handler
for that element.
• then a click event is sent to the box element.
• than a click event is sent to it's parent etc.
<div id="box">
<div class=tile>0</div>
<div class=tile>1</div>
<div class=tile>2</div>
…
<div class=tile>99</div>
</div>
stopping the bubble
• return 'false' as the result of the event handler.
• call the events stopImmediatePropagation()
function.
$('.Tile').click(
function(evt)
{
alert('Tile: ' + $(this).text());
evt.stopImmediatePropagation();
// evt.cancelBubble for IE
});
stopping default behavior
• Some elements have default behavior such as submitting
the form on the page
• You can prevent this either on the element or when a form
receives a 'submit' event.
$('#submit').click(
function(evt)
{
if (!confirm('Reset Fields?'))
{
evt.preventDefault();
// IE: evt.returnValue = false;
}
});
event bubble gotchas
• all events bubble except for:
• focus
• blur
• If you use jQuery you can use focusin and focusout
events if you need ones that bubble.
contents of an event
{
charCode: integer

keyCode: integer 

currentTarget: EventTarget // not defined in
IE

target: EventTarget // srcElement in IE

clientX, clientY: long

offsetX, offsetY: integer

pageX, pageY: integer // not in IE

timeStamp: unsigned long // FireFox, iOS,

IE issues

type: string

...
}
charCode / keyCode
• charCode:keyPress events (printable chars)
• keyCode: keyDown / keyUp (virtual code)
• keyDown / keyUp can be different keyCodes.
• Also see: altKey, ctrlKey, metaKey, shiftKey
target / currentTarget
• target is the element the event was "fired" at
• currentTarget is the element that has an
event handler that is processing that event
target:
<div class="Tile">68
</div>
currentTarget:
<div class="Box">…
</div>
$('.Box').on('click', function(evt){…});
Legacy IE uses
srcElement
instead of target
client / offset / pageX,Y
Position of mouse / touch relative to:
• clientX/Y: window, regardless of whether the page is scrolled
• offsetX/Y: target element
• pageX/Y: page, consistent as the page is scrolled
• screenX/Y: top left of monitor

FireFox only recently started supporting offsetX
Legacy IE Support is mixed for some of these
jQuery is your friend, emulates what is missing

(most of the time).
timeStamp
• Time event occurred, in milliseconds!
• If only that was the case!
• Might be in milliseconds, might be some other
number range.
• Often it is zero.
• Generally the numbers get bigger, but be very
very careful with assumptions about timeStamp.
triggering events
• You can fake events by triggering them on
elements:
$('#MyButton').click();
$('#MyForm').submit();
$('#MyInputField').focus();
• You can pass characters, etc if you construct
your own events.
• You can roll your own events or let a library (eg:
jQuery) handle it for you.
custom events
• You can invent your own events, send and receive
them:

$('#MyButton).on('colorChange',

function(evt, newColor)

{

$(this).css('background-color', newColor);
});
$('#MyButton').trigger('colorChange', ['blue']);

Sites
w3schools.com/jsref/dom_obj_event.asp
api.jquery.com/category/events/
caniuse.com
Tools
Chrome Debugging Tools
Safari iOS Debugger / Emulator
github.com/yphoenix/jsEventTracer
On the Fly Tracer
$.getScript('http://yphoenix.github.io/
jsEventTracer/Demo/jsEventTracer.js');
// OR
(function(u)
{var s=document.createElement("script");s.setAttribute("
type","text/
javascript");s.setAttribute("src",u);document.getElement
sByTagName("head")[0].appendChild(s);})('http://
yphoenix.github.io/jsEventTracer/Demo/
jsEventTracer.js');
Books
JavaScript: The Good Parts
JavaScript: The Definitive Guide
JavaScript Pocket Reference
Secrets of the JavaScript Ninja
Lint
JSLint.com
JSHint.com
ESLint.org
FlowType.org
General Dev. Philosophy
• Nothing is ever what it seems.
• Expect the unexpected.
• Code Defensively.
• Use Good Tools

(build them if you need to).
Q & A
Yorick Phoenix
slides: bit.ly/FineArtJSEvents
yorick@issio.net
about.me/yorickphoenix | @scribblings | github.com/yphoenix

Contenu connexe

Tendances

The Open Web and what it means
The Open Web and what it meansThe Open Web and what it means
The Open Web and what it means
Robert Nyman
 
JavaScript APIs - The Web is the Platform - MozCamp, Buenos Aires
JavaScript APIs - The Web is the Platform - MozCamp, Buenos AiresJavaScript APIs - The Web is the Platform - MozCamp, Buenos Aires
JavaScript APIs - The Web is the Platform - MozCamp, Buenos Aires
Robert Nyman
 
JavaScript APIs - The Web is the Platform - MDN Hack Day, Santiago, Chile
JavaScript APIs - The Web is the Platform - MDN Hack Day, Santiago, ChileJavaScript APIs - The Web is the Platform - MDN Hack Day, Santiago, Chile
JavaScript APIs - The Web is the Platform - MDN Hack Day, Santiago, Chile
Robert Nyman
 
JavaScript APIs - The Web is the Platform - MDN Hack Day, Montevideo
JavaScript APIs - The Web is the Platform - MDN Hack Day, MontevideoJavaScript APIs - The Web is the Platform - MDN Hack Day, Montevideo
JavaScript APIs - The Web is the Platform - MDN Hack Day, Montevideo
Robert Nyman
 
JavaScript APIs - The Web is the Platform - MDN Hack Day - Buenos Aires
JavaScript APIs - The Web is the Platform - MDN Hack Day - Buenos AiresJavaScript APIs - The Web is the Platform - MDN Hack Day - Buenos Aires
JavaScript APIs - The Web is the Platform - MDN Hack Day - Buenos Aires
Robert Nyman
 
Week 4 - jQuery + Ajax
Week 4 - jQuery + AjaxWeek 4 - jQuery + Ajax
Week 4 - jQuery + Ajax
baygross
 
HTML5, The Open Web, and what it means for you - MDN Hack Day, Sao Paulo
HTML5, The Open Web, and what it means for you - MDN Hack Day, Sao PauloHTML5, The Open Web, and what it means for you - MDN Hack Day, Sao Paulo
HTML5, The Open Web, and what it means for you - MDN Hack Day, Sao Paulo
Robert Nyman
 
HTML5 & The Open Web - at Nackademin
HTML5 & The Open Web -  at NackademinHTML5 & The Open Web -  at Nackademin
HTML5 & The Open Web - at Nackademin
Robert Nyman
 
Netvibes UWA workshop at ParisWeb 2007
Netvibes UWA workshop at ParisWeb 2007Netvibes UWA workshop at ParisWeb 2007
Netvibes UWA workshop at ParisWeb 2007
Netvibes
 
Knockout.js presentation
Knockout.js presentationKnockout.js presentation
Knockout.js presentation
Scott Messinger
 

Tendances (20)

Client Web
Client WebClient Web
Client Web
 
Js events
Js eventsJs events
Js events
 
Html events with javascript
Html events with javascriptHtml events with javascript
Html events with javascript
 
The Open Web and what it means
The Open Web and what it meansThe Open Web and what it means
The Open Web and what it means
 
JavaScript APIs - The Web is the Platform - MozCamp, Buenos Aires
JavaScript APIs - The Web is the Platform - MozCamp, Buenos AiresJavaScript APIs - The Web is the Platform - MozCamp, Buenos Aires
JavaScript APIs - The Web is the Platform - MozCamp, Buenos Aires
 
JavaScript APIs - The Web is the Platform - MDN Hack Day, Santiago, Chile
JavaScript APIs - The Web is the Platform - MDN Hack Day, Santiago, ChileJavaScript APIs - The Web is the Platform - MDN Hack Day, Santiago, Chile
JavaScript APIs - The Web is the Platform - MDN Hack Day, Santiago, Chile
 
JavaScript APIs - The Web is the Platform - MDN Hack Day, Montevideo
JavaScript APIs - The Web is the Platform - MDN Hack Day, MontevideoJavaScript APIs - The Web is the Platform - MDN Hack Day, Montevideo
JavaScript APIs - The Web is the Platform - MDN Hack Day, Montevideo
 
JavaScript APIs - The Web is the Platform - MDN Hack Day - Buenos Aires
JavaScript APIs - The Web is the Platform - MDN Hack Day - Buenos AiresJavaScript APIs - The Web is the Platform - MDN Hack Day - Buenos Aires
JavaScript APIs - The Web is the Platform - MDN Hack Day - Buenos Aires
 
Week 4 - jQuery + Ajax
Week 4 - jQuery + AjaxWeek 4 - jQuery + Ajax
Week 4 - jQuery + Ajax
 
HTML5, The Open Web, and what it means for you - MDN Hack Day, Sao Paulo
HTML5, The Open Web, and what it means for you - MDN Hack Day, Sao PauloHTML5, The Open Web, and what it means for you - MDN Hack Day, Sao Paulo
HTML5, The Open Web, and what it means for you - MDN Hack Day, Sao Paulo
 
HTML5 & The Open Web - at Nackademin
HTML5 & The Open Web -  at NackademinHTML5 & The Open Web -  at Nackademin
HTML5 & The Open Web - at Nackademin
 
DHTML - Events & Buttons
DHTML - Events  & ButtonsDHTML - Events  & Buttons
DHTML - Events & Buttons
 
Events
EventsEvents
Events
 
jQuery Best Practice
jQuery Best Practice jQuery Best Practice
jQuery Best Practice
 
Getting classy with ES6
Getting classy with ES6Getting classy with ES6
Getting classy with ES6
 
JavaScript & Dom Manipulation
JavaScript & Dom ManipulationJavaScript & Dom Manipulation
JavaScript & Dom Manipulation
 
FuncUnit
FuncUnitFuncUnit
FuncUnit
 
Knockout.js
Knockout.jsKnockout.js
Knockout.js
 
Netvibes UWA workshop at ParisWeb 2007
Netvibes UWA workshop at ParisWeb 2007Netvibes UWA workshop at ParisWeb 2007
Netvibes UWA workshop at ParisWeb 2007
 
Knockout.js presentation
Knockout.js presentationKnockout.js presentation
Knockout.js presentation
 

Similaire à The Fine Art of JavaScript Event Handling

jQuery 1.7 Events
jQuery 1.7 EventsjQuery 1.7 Events
jQuery 1.7 Events
dmethvin
 
Introj Query Pt2
Introj Query Pt2Introj Query Pt2
Introj Query Pt2
kshyju
 
ARTDM 170, Week 7: Scripting Interactivity
ARTDM 170, Week 7: Scripting InteractivityARTDM 170, Week 7: Scripting Interactivity
ARTDM 170, Week 7: Scripting Interactivity
Gilbert Guerrero
 
Solving Problems with YUI3: AutoComplete
Solving Problems with YUI3: AutoCompleteSolving Problems with YUI3: AutoComplete
Solving Problems with YUI3: AutoComplete
IsaacSchlueter
 

Similaire à The Fine Art of JavaScript Event Handling (20)

Javascript Browser Events.pdf
Javascript Browser Events.pdfJavascript Browser Events.pdf
Javascript Browser Events.pdf
 
jQuery besic
jQuery besicjQuery besic
jQuery besic
 
JavaScript_Events.pptx
JavaScript_Events.pptxJavaScript_Events.pptx
JavaScript_Events.pptx
 
jQuery 1.7 Events
jQuery 1.7 EventsjQuery 1.7 Events
jQuery 1.7 Events
 
DOM Events
DOM EventsDOM Events
DOM Events
 
Events.pdf
Events.pdfEvents.pdf
Events.pdf
 
JAVA PROGRAMMING- GUI Programming with Swing - The Swing Buttons
JAVA PROGRAMMING- GUI Programming with Swing - The Swing ButtonsJAVA PROGRAMMING- GUI Programming with Swing - The Swing Buttons
JAVA PROGRAMMING- GUI Programming with Swing - The Swing Buttons
 
Unit3.pptx
Unit3.pptxUnit3.pptx
Unit3.pptx
 
Introj Query Pt2
Introj Query Pt2Introj Query Pt2
Introj Query Pt2
 
Attribute actions
Attribute actionsAttribute actions
Attribute actions
 
WP - Unit I.ppt
WP - Unit I.pptWP - Unit I.ppt
WP - Unit I.ppt
 
JavaScript
JavaScriptJavaScript
JavaScript
 
JavaScript
JavaScriptJavaScript
JavaScript
 
Chap - 2 - Event Handling.pptx
Chap - 2 - Event Handling.pptxChap - 2 - Event Handling.pptx
Chap - 2 - Event Handling.pptx
 
Look Up Mobile Javascript
Look Up Mobile JavascriptLook Up Mobile Javascript
Look Up Mobile Javascript
 
ARTDM 170, Week 7: Scripting Interactivity
ARTDM 170, Week 7: Scripting InteractivityARTDM 170, Week 7: Scripting Interactivity
ARTDM 170, Week 7: Scripting Interactivity
 
B2. activity and intent
B2. activity and intentB2. activity and intent
B2. activity and intent
 
09events
09events09events
09events
 
Solving Problems with YUI3: AutoComplete
Solving Problems with YUI3: AutoCompleteSolving Problems with YUI3: AutoComplete
Solving Problems with YUI3: AutoComplete
 
The Inclusive Web: hands-on with HTML5 and jQuery
The Inclusive Web: hands-on with HTML5 and jQueryThe Inclusive Web: hands-on with HTML5 and jQuery
The Inclusive Web: hands-on with HTML5 and jQuery
 

Dernier

VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
dharasingh5698
 
notes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptnotes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.ppt
MsecMca
 
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Dernier (20)

Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
 
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
NFPA 5000 2024 standard .
NFPA 5000 2024 standard                                  .NFPA 5000 2024 standard                                  .
NFPA 5000 2024 standard .
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
 
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
 
Block diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptBlock diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.ppt
 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
 
notes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptnotes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.ppt
 
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced LoadsFEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
 
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdf
 
Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptx
 
Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the start
 

The Fine Art of JavaScript Event Handling

  • 1. The Fine Art of JavaScript Event Handling Yorick Phoenix slides: bit.ly/FineArtJSEvents yorick@issio.net about.me/yorickphoenix | @scribblings | github.com/yphoenix
  • 2. General Dev. Philosophy • Nothing is ever what it seems. • Expect the unexpected. • Code Defensively. • Use Good Tools
 (build them if you need to).
  • 3. Quick Event Recap • User interaction creates events. • Which event depends on the element and the action. • DOM Level 0 and DOM Level 2 Models. • Legacy IE and DOM Event Models. • jQuery is your friend.
  • 5. DOM 0 <button onclick="alert('Hello, World!')"> Click Me! </button> https://jsfiddle.net/hhj9uu8x/ • No separation of UI and Event handling. • Of limited use due to limited power, flexibility and scaleability.
  • 6. DOM 2 & 3 <button id="moon">Click Me!</button> $('#moon').click( function(evt) { alert("Hello, world"); }); https://jsfiddle.net/0dqc9s8p/
  • 8. event caveats • Don't expect to get the events in the same order. • Don't expect to get all of the same events. • Don't expect the fields of the event object to be complete or correct. • Each Browser / platform / version writes their own rules.
  • 9. Not Sure which events? TRY IT EXPERIMENT
  • 10. detecting user hit • Don't look at mousedown or mouseup events. • look for 'click' events. • This works for touch devices. • This works for assisted devices.
  • 11. click event gotchas • disabled buttons receive clicks in IE • readonly text fields get click events • readonly or disabled div elements get click events
  • 12. detecting content change • Don't look at click, keydown, keyup, keypress, etc events. • look for 'change' or 'input' events. • This works for touch devices. • This works for assisted devices.
  • 13. input vs change • input events indicate that an element received some input somehow. • a change event (normally) indicates that an element has finished changing. • change events often fire after loss of focus.
  • 14. input event gotchas • checkboxes don't get input events • input type="file" // receives input events in IE • Editable Divs don't get input events in IE but do everywhere else, you have to use keyPress too (ugh)
  • 15. change event gotchas • unset radio buttons don't get a change event • some elements send an input and change event for every user input • input type="date" or "time" • input type="range" // Firefox only
  • 16. touch events • Get mapped to mouse & click events • touchstart, touchmove, touchend • mouseover, mousemove, mousedown, mouseup, click • 300ms delay
  • 17. avoiding the 300ms delay • <meta name="viewport"
 content="width=device-width, user-scalable=no"> • Handle touchstart, touchmove, touchend events • Use a library: FTLabs FastClick or Tappy • http://www.sitepoint.com/5-ways-prevent-300ms- click-delay-mobile-devices/
  • 18. too many event handlers? • if you had a grid of 100 elements and wanted to detect a click on each element? • How many event handlers would you need? <div id="box"> <div class=tile>0</div> <div class=tile>1</div> <div class=tile>2</div> … <div class=tile>99</div> </div>
  • 19. too many event handlers? $('.tile').click( function() { alert($(this).text()); }); • 100 click handlers, one for every Tile Element. <div id="box"> <div class=tile>0</div> <div class=tile>1</div> <div class=tile>2</div> … <div class=tile>99</div> </div> • How many does this install?
  • 20. event bubbling is better $('.box').on('click', function(evt) { alert($(evt.target).text()); }); • One event handler on the surrounding box element. <div id="box"> <div class=tile>0</div> <div class=tile>1</div> <div class=tile>2</div> … <div class=tile>99</div> </div> • How many does this install?
  • 21. event bubbling? • All events are targeted at an element. • If that element doesn't have an event handler (that completely handles the event). • The event is offered to event handlers of the parent element, and its parent, etc. • Until the top of the hierarchy is reached (document) • Or an event handler indicates that bubbling should stop.
  • 22. bubble example? • a click on a tile sends a click event to the event handler for that element. • then a click event is sent to the box element. • than a click event is sent to it's parent etc. <div id="box"> <div class=tile>0</div> <div class=tile>1</div> <div class=tile>2</div> … <div class=tile>99</div> </div>
  • 23. stopping the bubble • return 'false' as the result of the event handler. • call the events stopImmediatePropagation() function. $('.Tile').click( function(evt) { alert('Tile: ' + $(this).text()); evt.stopImmediatePropagation(); // evt.cancelBubble for IE });
  • 24. stopping default behavior • Some elements have default behavior such as submitting the form on the page • You can prevent this either on the element or when a form receives a 'submit' event. $('#submit').click( function(evt) { if (!confirm('Reset Fields?')) { evt.preventDefault(); // IE: evt.returnValue = false; } });
  • 25. event bubble gotchas • all events bubble except for: • focus • blur • If you use jQuery you can use focusin and focusout events if you need ones that bubble.
  • 26. contents of an event { charCode: integer
 keyCode: integer 
 currentTarget: EventTarget // not defined in IE
 target: EventTarget // srcElement in IE
 clientX, clientY: long
 offsetX, offsetY: integer
 pageX, pageY: integer // not in IE
 timeStamp: unsigned long // FireFox, iOS,
 IE issues
 type: string
 ... }
  • 27. charCode / keyCode • charCode:keyPress events (printable chars) • keyCode: keyDown / keyUp (virtual code) • keyDown / keyUp can be different keyCodes. • Also see: altKey, ctrlKey, metaKey, shiftKey
  • 28. target / currentTarget • target is the element the event was "fired" at • currentTarget is the element that has an event handler that is processing that event target: <div class="Tile">68 </div> currentTarget: <div class="Box">… </div> $('.Box').on('click', function(evt){…}); Legacy IE uses srcElement instead of target
  • 29. client / offset / pageX,Y Position of mouse / touch relative to: • clientX/Y: window, regardless of whether the page is scrolled • offsetX/Y: target element • pageX/Y: page, consistent as the page is scrolled • screenX/Y: top left of monitor
 FireFox only recently started supporting offsetX Legacy IE Support is mixed for some of these jQuery is your friend, emulates what is missing
 (most of the time).
  • 30. timeStamp • Time event occurred, in milliseconds! • If only that was the case! • Might be in milliseconds, might be some other number range. • Often it is zero. • Generally the numbers get bigger, but be very very careful with assumptions about timeStamp.
  • 31. triggering events • You can fake events by triggering them on elements: $('#MyButton').click(); $('#MyForm').submit(); $('#MyInputField').focus(); • You can pass characters, etc if you construct your own events. • You can roll your own events or let a library (eg: jQuery) handle it for you.
  • 32. custom events • You can invent your own events, send and receive them:
 $('#MyButton).on('colorChange',
 function(evt, newColor)
 {
 $(this).css('background-color', newColor); }); $('#MyButton').trigger('colorChange', ['blue']);

  • 34. Tools Chrome Debugging Tools Safari iOS Debugger / Emulator github.com/yphoenix/jsEventTracer
  • 35. On the Fly Tracer $.getScript('http://yphoenix.github.io/ jsEventTracer/Demo/jsEventTracer.js'); // OR (function(u) {var s=document.createElement("script");s.setAttribute(" type","text/ javascript");s.setAttribute("src",u);document.getElement sByTagName("head")[0].appendChild(s);})('http:// yphoenix.github.io/jsEventTracer/Demo/ jsEventTracer.js');
  • 36. Books JavaScript: The Good Parts JavaScript: The Definitive Guide JavaScript Pocket Reference Secrets of the JavaScript Ninja
  • 38. General Dev. Philosophy • Nothing is ever what it seems. • Expect the unexpected. • Code Defensively. • Use Good Tools
 (build them if you need to).
  • 39. Q & A Yorick Phoenix slides: bit.ly/FineArtJSEvents yorick@issio.net about.me/yorickphoenix | @scribblings | github.com/yphoenix